vue之el-upload自定义上传文件
vue之el-upload自定义上传文件本篇文章记录一下使用el-upload的相关属性以及自定义上传文件的代码段代码段如下:<el-form-item label="添加附件"><el-uploadclass="upload-demo"accept=".xls, .xlsx, .docx, ....
·
vue之el-upload自定义上传文件
本篇文章记录一下使用el-upload的相关属性以及自定义上传文件的代码段
代码段如下:
<el-form-item label="添加附件">
<el-upload
class="upload-demo"
accept=".xls, .xlsx, .docx, .jpg, .jpeg, .png, .zip"
ref="upload"
action="action"
:http-request="uploadFile"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-success="onSuccess"
:on-error="onError"
:before-upload="onBeforeUpload"
:limit="3"
:on-exceed="handleExceed"
:file-list="fileList"
:auto-upload="false"
>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button
style="margin-left: 10px;"
size="small"
type="success"
@click="submitFile"
>上传附件</el-button>
<div
slot="tip"
class="el-upload__tip"
style="color:red"
>支持文件类型:xls、 xlsx、 docx、 jpg、 jpeg、 png、 zip; 支持文件大小:2M以内; 如果是多文件上传请选择压缩文件格式(.zip)</div>
</el-upload>
</el-form-item>
<script>
submitFile() {
this.$refs.upload.submit();
},
uploadFile(file) {
var filelist = new FormData();
//添加参数
filelist.append("file", file.file);
filelist.append("id", this.reportForm.id);
filelist.append("name", this.reportForm.name);
filelist.append("publisher", this.reportForm.publisher);
this.$http
.post(
"http://101.37.83.223:8181/uploadDocument",
filelist,
{ headers: { "Content-Type": "multipart/form-data" } }
)
.then(res => {
this.$message.success("文件上传成功");
})
.catch(err => {
this.$message.error("文件上传失败");
});
this.fileList = [];
},
</script>
上述el-upload的属性相关说明:
accept:可以自定义上传的文件类型,但是要真正起到限制的作用,需要在:before- upload钩子中限制文件类型
action:ui默认上传的地址,不能为空。自定义时可以设置为任意字符串
on-success,on-error:文件上传成功、文件上传失败返回的钩子函数,自定义文件上传时失效。
limit:限制文件上传的个数
on-exceed:文件超出个数限制时的钩子
file-list:上传文件的列表
http-request :覆盖默认的上传行为,可以自定义上传的实现。
关于自定义上传文件注意的几点:
(1)使用自定义上传后,on-success,on-error等钩子函数会失效,需要重新设置上传成功的相关提醒
(2)在自定义中,如果要进行参数的传递。利用FormData对象的append方法进行模拟表单赋值,如上例所示。
(3)上述示例代码中使用的手动上传方式,所以要调用this.$refs.upload.submit()方法,来触发http-request钩子。
更多推荐
已为社区贡献2条内容
所有评论(0)