当前位置:网站首页>ant-design form form verification upload component (with personal packaged upload component)
ant-design form form verification upload component (with personal packaged upload component)
2022-07-30 09:07:00 【Li Jianyi】
ant-design form表单校验upload组件(Upload component with personal package)
uploadComponent required validation
最近一直在使用 ant-design 组件库开发,The project suddenly said that the attachment needs to be uploaded in the form“必传”,Searching through the major documents has no answer,Finally, this requirement is achieved with custom validation.
使用 a-form-model Form component development
<template>
<a-form-model ref="ruleForm" :rules="rules" :model="infoFrom">
<a-form-model-item label="上传附件" prop="files">
<a-upload
name="files"
:multiple="false"
:file-list="fileList"
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
:headers="headers"
@change="handleChange"
>
<a-button> <a-icon type="upload" /> 上传附件 </a-button>
</a-upload>
</a-form-model-item>
<a-form-model-item>
<a-button type="primary" html-type="submit" @click="submitForm">
提交
</a-button>
</a-form-model-item>
</a-form-model>
</template>
<script>
export default {
data() {
return {
fileList: [],
rules: {
files: [{required:true, validator:this.uploadFileChange, trigger:'change'}]
}
}
},
methdos: {
// Custom upload attachment verification
uploadFileChange(rule, value, callback) {
if(this.fileList.length === 0) {
return callback('请选择需要上传的文件')
}else {
return true;
}
},
// 提交方法
submitForm() {
this.$refs.ruleForm.validate(valid => {
if (valid) {
console.log('触发保存');
}
})
}
}
}
</script>
Personal package upload attachments
Based on the business needs of the project,Second package ant-design 的 upload 组件,Some places haven't been done yet,Supplementary after improvement~
主文件
<!-- Upload file upgrades -->
<template>
<div class="upload-container">
<a-upload-dragger
name="files"
:class="{'uploadHide': isState==='detail'}"
:disabled="disabled"
:list-type="fileListType"
:multiple="multiple"
:showUploadList="{
showPreviewIcon: isShowPreviewIcon,
showRemoveIcon: isShowRemoveIcon,
showDownloadIcon: isShowDownloadIcon
}"
:openFileDialogOnClick="true"
:headers="headers"
:file-list="fileList"
:data="data"
:action="uploadUrl"
:before-upload="beforeUpload"
@change="handleChange"
@preview="handlePreview"
@download="handleDownload"
>
<p class="ant-upload-drag-icon">
<a-icon type="inbox" />
</p>
<p class="ant-upload-text">
Drag and drop files here to upload
</p>
</a-upload-dragger>
<span class="upload-accept" v-if="isState!=='detail'">
<a-icon type="exclamation-circle" />
支持 {
{ acceptHint }} 文件格式,最大不超过 {
{ size }} M
</span>
</div>
</template>
<script>
import FileDetail from './file-detail'; // Preview components online,You need to call the online preview interface in the service
export default {
name: "upload-plus",
props: {
// Upload file status [detail(只读状态)、opera(操作状态)]
// detail(只读状态,The delete button must not be displayed,Only the View and Download buttons are displayed)
isState: {
type: String,
default: ()=>{
return 'opera'
}
},
// Whether to disable uploading of attachments
disabled: {
type: Boolean,
default: ()=>{
return false;
}
},
// 是否允许上传多个文件
multiple: {
type: Boolean,
default: ()=>{
return false;
}
},
// 限制文件上传个数
limit: {
type: Number,
default: ()=>{
return 0
}
},
// Prompt for file types that are allowed to be uploaded
accept: {
type: Array,
default: ()=>{
return ['doc','docx','xls','xlsx','jpg','jpeg','png','pdf','txt']
}
},
// Allowed upload file size hint(MB为单位)
size: {
type: Number,
default: ()=>{
return 200;
}
},
// Upload list built-in styles
fileListType: {
type: String,
default: ()=>{
return 'text';
}
},
// Whether to show the preview chart
showPreviewIcon: {
type: Boolean,
default: ()=>{
return true
}
},
// Whether to display the delete chart
showRemoveIcon: {
type: Boolean,
default: ()=>{
return true
}
},
// Whether to show download charts
showDownloadIcon: {
type: Boolean,
default: ()=>{
return true
}
},
// 文件列表
fileList: {
type: Array,
default: () => {
return []
}
},
// 数据
data: {
type: Object,
default: ()=>{
return {}
}
},
// 上传文件的Url
uploadUrl: {
type: String,
default: ()=>{
return '/api/upload'
}
},
},
data() {
return {
// file request header
headers: {
Authorization: 'Bearer ' + JSON.parse(localStorage.getItem('access-Token')).value,
}
}
},
computed: {
// Returns the file prompt information
acceptHint() {
if(this.accept.length === 0) {
return '未知';
}else {
if(this.accept.indexOf('*') === -1) {
return this.accept.join('、');
}else {
return '所有'
}
}
},
// Whether to enable the file preview button
isShowPreviewIcon() {
return this.showPreviewIcon;
},
// Whether to enable the file download button
isShowDownloadIcon() {
return true;
},
// Whether to enable the file delete button
isShowRemoveIcon() {
if(this.showRemoveIcon && this.isState !== 'detail') {
return true
}else {
return false;
}
},
},
methods: {
/**
* 上传文件前触发
* @param {Object} file 文件数据
*/
beforeUpload(file) {
// File name verification
if(file.name.substring(0,file.name.indexOf(".")).length>50){
this.$message.error('Upload file name must not exceed50字');
return false;
}
// 文件类型校验
let fileExt = file.name.slice(file.name.lastIndexOf('.')+1);
if(this.accept.indexOf(fileExt) === -1) {
this.$message.error('Uploading illegal file types is prohibited');
return false;
}
// 文件大小校验
let fileSize = file.size / 1024 / 1024;
if(fileSize > this.size) {
this.$message.error('只允许上传' + this.size + 'M一下的文件');
return false;
}
return true;
},
/**
* Triggered when uploaded file changes
* @param {Object} info 文件信息
* */
handleChange(info) {
let fileList = [...info.fileList].filter(item => {
return item.status !== undefined
});
if (this.limit !== 0) {
fileList = fileList.slice(-this.limit);
}
fileList = fileList.map(file => {
if (file.response) {
file.url = file.response.url;
}
return file;
});
this.$emit('update:fileList', fileList);
},
/**
* File preview callback
* @param {Object} file 文件
* */
handlePreview(file) {
console.log("Trigger file preview");
},
/**
* 文件下载回调
* @param {Object} file 文件
* */
handleDownload(file) {
let fileName = file.name,
filePathId = file.response.data.data[0].fileId;
const a = document.createElement("a");
a.download = `${fileName}`;
a.href = "/api/download/" + filePathId;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
},
}
}
</script>
<style lang="less" scoped>
.uploadHide {
& /deep/ .ant-upload.ant-upload-drag {
display: none;
}
}
.upload-accept {
font-size: 1em;
color: gray;
}
</style>
边栏推荐
猜你喜欢
typescript6 - simplify the steps to run ts
typescript5 - compile and install ts code
The blockbuster IP that has been popular in the world for 25 years, the new work has become a script paradise
HashSet和LinkedHashSet
ES报错处理-mapper [xx.xx] of different type, current_type [text], merged_type [keyword]
【Kotlin 中的类和继承】
【sleuth + zipkin 服务链路追踪】
看完这100个客户需求,我终于知道企业文档管理的秘密
SQL窗口函数
实现定时器
随机推荐
代币(双代币)系统研究
【Flask框架①】——Flask介绍
SQL的ROUND函数用法及其实例
Why does typescript2-typescript add type support to js
41.【vector应用操作2】
开创ETC生态建设新格局 JASMINER新一批X4服务器陆续发出
Selected as one of the "Top Ten Hard Core Technologies", explaining the technical points of Trusted Confidential Computing (TECC) in detail
Dynamic Lead Time Promising
数据库连接池的使用
电路分析:运放和三极管组成的恒流源电路
File类
基于JSP实现校园二手交易平台
input标签的tabindex属性 & a标签的tabindex属性
如何使用 Jmeter 进行抢购、秒杀等场景下,进行高并发?
2022年施工企业数字化转型思考,施工企业数字化转型之路
立创EDA——PCB的走线(五)
【无标题】
智能存储柜——解决您的存储需求
Splunk tag 的利用场景
ES:模板字符串的使用