参考代码会放到最后
1.上传
用el-upload组件上传文件
<el-upload
class="upload-file"
action="xxxxxx/xxxxxxx/xxxxxxxx"
:headers="xxxxxx"
:before-upload="beforeUploadFile"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
multiple
:limit="1"
:on-exceed="handleExceed"
:on-success="uploadSuccess"
:file-list="fileList"
:data="uploadParams">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">请上传图片、表格或文档,大小不得超过5M</div>
</el-upload>
- action中填写文件上传的接口地址,如果上传需要携带header信息,在:headers="xxxxxx"中填写。
- :file-list是已上传的文件列表。
- uploadParams是我自己定义的参数,因为我的文件上传接口action="xxx"需要一个额外的参数,如果你的文件接口不需要参数, :data里就不用写了,空引号就行。
- :limit 限制文件个数。
参数定义:
fileList: [],
confirmForm: {
fileUrl:'', // 记录文件上传成功后的下载连接
fileName:'', // 记录文件的名字
},
uploadParams:{
fileName:'' // 我的上传接口需要一个fileName的入参,如果还需要其他入参,可以一并加到uploadParams对象里
},
- 注意:this.confirmForm、this.uploadParams是我自己额外定义的参数,因为我的功能只需要上传一个文件就够了,并且我的文件上传接口会返回给我两个参数“fileUrl”和“fileName”,所以我直接用自定义的参数记录下文件的信息。这一块需要各位根据自己业务需要修改。
- 如果需要多个文件,要么直接用已经定义好的:file-list=“fileList”,从fileList中去取文件列表。
相关方法:
//文件上传之前
beforeUploadFile(file) {
const size = file.size / 1024/ 1024
if (size > 5) {
this.$message({
message: '文件大小不得大于5M',
duration: 2000,
showClose: true,
type: 'warning'
});
return false;
}
var FileExt = file.name.replace(/.+\./, "");
if (["xls", "xlsx","pdf","jpg","jpeg","png","doc","docx","txt"].indexOf(FileExt.toLowerCase()) === -1) {
this.$message({
message: '上传文件只能是图片、表格或文档',