2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > element-ui el-upload实现上传文件以及简单的上传文件格式验证

element-ui el-upload实现上传文件以及简单的上传文件格式验证

时间:2018-06-25 23:54:47

相关推荐

element-ui el-upload实现上传文件以及简单的上传文件格式验证

在后台管理系统中总是会用到上传文件的功能,

想实现的样式如下:(实现上传文件后,在input输入框显示文件名 )

结构代码如下:

<el-form-item label="使用说明" class="uploadMain" prop="instruction"><el-inputclass="uploadInput"v-model="productVO.instruction"style="width: 75%"placeholder="请上传pdf格式的使用说明文件":disabled="true"><el-uploadslot="append"class="uploadbox"ref="upload"name="file"accept=".pdf" //接受上传文件的格式,此处会默认打开上传时筛选.pdf格式:show-file-list="false":multiple="false" //如果想要一次选择多个文件 mulitiple为trueaction="upload":on-change="onChange":auto-upload="false" //自动上传,如果此处为true 选择完文件就直接上传了><!-- class="uploadbtn" --><el-button class="uploadbtn"></el-button></el-upload></el-input></el-form-item>

由于上述结构代码打开上传文件时会自动筛选accept的文件格式,但是在用户选择时仍可以自己选择全部文件,所以需要前端对上传文件进行初步的格式检验

前端部分上传文件初步检验js代码如下:

onChange(file) {// 校验格式if (['application/pdf'].indexOf(file.raw.type) == -1) {this.$message.error('请上传正确的pdf格式');return false;}this.productVO.instruction = file.name;this.productVO.instructionFile = file.raw; //上传文件时需要用到二进制,所以这里文件取值为file.raw},

上传至接口时js代码如下:

submit(){const formData = new FormData();formData.append('instruction', this.productVO.instruction);formData.append('instructionFile',this.productVO.instructionFile);//调用接口this.$post('/product/create',formData,{baseURL:'/',header:{isloading: true,'Content-Type': 'multipart/form-data'}).then()}

此处涉及到文件的不同格式,列举一些常用的文件格式

附加:当上传文件为多个时,具体代码如下:

<el-form-item label="数据" class="uploadMain" prop="entity"><el-inputclass="uploadInput"v-model="productVO.entity"style="width: 75%"placeholder="请上传完整的tif/tiff/shp格式的数据文件":disabled="true"><el-uploadslot="append"class="uploadbox"ref="upload"name="file"accept=".tif,.tiff,.shp,.dbf,.prj,.sbn,.sbx,.shx":show-file-list="false"multiple:file-list="this.productVO.fileList"action="upload":on-change="onChange":auto-upload="false"><!-- class="uploadbtn" --><el-button class="uploadbtn"></el-button></el-upload></el-input><div style="color: #ffc230">此处是文本说明</div></el-form-item>

js代码如下:

onChange(file,fileList) {// 校验格式if (['image/tiff', ''].indexOf(file4.raw.type) == -1) {this.$message.error('请上传正确的tif/tiff/shp格式');return false;}else{this.productVO.fileList=fileListconsole.log(this.productVO.fileList)var listName=[]this.productVO.fileList.forEach(function(e){listName.push(e.name)})var listFileRaw=[]this.productVO.fileList.forEach(function(e){listFileRaw.push(e.raw)})this.productVO.entity = listName; //文本框显示所有的文件名this.productVO.entityFile = listFileRaw;}},

接口上传文件时formData传参改动如下:

this.productVO.entityFile.forEach(element => {formData.append('entityFile', element)})

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。