对于文件上传,实际项目中我们的需求一般分为两种:
1. 对于单个文件的上传,直接上传到服务器;
官网api:http://element-cn.eleme.io/#/zh-CN/component/upload
<el-upload
class="avatar-uploader"
action=""
:http-request="uploadimage"
:before-upload="beforeAvatarUpload"
name="fileData"
:show-file-list="false"
:on-success="handleAvatarSuccess"
>
<img v-if="bannerRuleForm.imageUrl" :src="bannerRuleForm.imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
js:
uploadimage(item) {
let formData = new FormData();
let file = item.file;
formData.append('file', file);
uploadImg(formData).then(res => {
this.bannerRuleForm.imageUrl = res.data.url;
});
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg' || 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
handleAvatarSuccess(res, file) {
this.bannerRuleForm.imageUrl = URL.createObjectURL(file.raw);
},
2. 和表单一起通过FormData 上传;
<el-form-item label="文件" required>
<el-upload v-model="ruleForm.file" ref="upload" action="" :http-request="uploadFileDrawer"
:show-file-list="false" :file-list="drawerFileList" :auto-upload="false" :limit="1"
:on-change="handleChange" :on-exceed="exceedFile">
<el-link :underline="false" slot="trigger" icon="el-icon-link" type="info">添加文件</el-link>
</el-upload>
<div class="file-list">
<span v-for="(item, index) in drawerFileList" :key="item.url">
<el-link class="file-link" :underline="false" icon="el-icon-link" type="primary"
:href="item.url" target="_blank">{{ item.name }}</el-link>
<i @click="delete_drawerFileList(index)" class="el-icon-delete el-icon--right"></i>
</span>
</div>
</el-form-item>
js:
// 文件超出个数限制时的钩子
exceedFile(files, fileList) {
this.$message.error('只能选择1个文件');
},
//上传文件让第二次覆盖第一的文件
handleChange(file, fileList) {
this.ruleForm.file = file.raw;
this.drawerFileList = fileList;
},
delete_drawerFileList(i) {
this.drawerFileList.splice(i, 1);
},
uploadFileDrawer(params) {
console.log(params, '00000');
let formData = new FormData();
formData.append('file', params.file);
},
submitForm(formName) {
let that = this;
this.$refs[formName].validate(async (valid) => {
if (valid) {
if (this.drawerFileList.length == 0) {
this.$message.error('请上传附件');
return;
}
let formData = new FormData();
formData.append('file', this.ruleForm.file);
formData.append('fileVersion', this.ruleForm.fileVersion);
that.inSubmit = true;
appApi.save(formData, function (res) {
that.inSubmit = false;
if (res.status != 200) return;
const response = res.response;
if (response.code !== 0) {
that.$message.error(response.msg);
return;
}
that.$message.success(response.msg);
that.cancel();
});
} else {
console.log('必填项未填完');
return false;
}
});
},