最近在写 vue 上传文件组件,遇到了一些问题,及时总结:
<el-upload
ref="uploadAttachment"
class="input"
:action="uploadUrl"
:data="{ path: 'baojia', isdate: '1' }"
:on-preview="handlePreviewGy"
:on-change="(file, list) => handleChangeBoomGy(file, list, boom)"
:on-success="(res, file, list) => handleSuccessBommGy(res, file, list, boom)"
:before-upload="beforeUploadGy"
:on-remove="(file, list) => removeBoomGy(file, list, boom)"
:before-remove="beforeRemoveGy"
:on-error="handleError"
multiple
:limit="3"
:file-list="boom.gy_fileList?boom.gy_fileList:[]">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">不超过10M</div>
</el-upload>
参数 | 说明 |
---|---|
action | 必选参数,上传的地址 |
data | 上传时附带的额外参数 |
on-preview | 点击文件列表中已上传的文件,触发函数,即点击已上传文件的效果 |
on-change | 添加文件、上传成功和上传失败时都会被调用 |
on-success | 文件上传成功时的钩子 |
before-upload | 上传文件之前的钩子,一般用作验证使用,例如大小,格式 |
on-remove | 文件列表移除文件时的钩子,删除后触发 |
before-remove | 删除文件之前的钩子,删除前触发,例如提示是否删除等等 |
on-error | 文件上传失败时的钩子 |
multiple | 是否支持多选文件 |
file-list | 上传的文件列表,上传成功后的数据需要赋值到这个字段内 |
limit | 最大允许上传个数 |
基本上常见也就是上面的字段,但是不仅仅就这么多,文档内有大量的字段,可以根据特殊定制
下面的js就是上面的对应方法,大家可以根据自己的需求去改
handlePreviewGy(file) {
let fileUrl = file.url;
window.open(fileUrl, '_blank');
},
handleChangeBoomGy(file, files, boom) {
boom.gy_fileList = files;
this.curBoom = boom;
},
handleSuccessBommGy(res, file, files, boom) {
if (res.code!=0) {
this.$message.error(res.message);
files.indexOf(file) > -1 && files.splice(files.indexOf(file), 1);
boom.gy_fileList = files;
return
}
boom.gy_fileList = files;
this.updateBoomMsg();
},
handleError(error, file, fileList) {
this.$message.error('上传失败,请稍后重试');
},
removeBoomGy(file, files, boom) {
boom.gy_fileList = files;
this.curBoom = boom;
this.updateBoomMsg();
},
beforeUploadGy(file) {
const isLt2M = file.size / 1024 / 1024 < 10;
if (!isLt2M) {
this.$message.error("上传图片大小不能超过 10MB!");
}
return isLt2M;
},
beforeRemoveGy(file, fileList) {
return this.$confirm(`确定删除该附件`);
},
问题点:
文件上传,httpcode码200,但是接口内业务码报错
正常报错,例如状态码:400,500之类的,好像 on-error 会触发
如果状态码是200,报错是由业务码来判断,就有点麻烦。
接口报错,但是组件却显示正常上传。
这时,我们就需要去处理 on-success 方法。如果是报错,则需要将当前这个文件去掉。
handleSuccess(res, file, files, boom) {
//接口报错
if (res.code!=0) {
this.$message.error(res.message);
//files 内找到对应的文件,然后删掉
files.indexOf(file) > -1 && files.splice(files.indexOf(file), 1);
boom.gy_fileList = files;
return
}
boom.gy_fileList = files;
this.updateBoomMsg();
},
总结:
vue操作的数据,请记住,数据是关键。接口报错,直接删除异常数据即可。我在这上面纠结了好久,经过多次测试,发现数据有异常,files 这个是所有文件数据,错误的也在理,直接删除即可。