视图代码
<el-form-item label="上传附件:" prop="">
<el-upload
class="upload-demo input1"
:action="uploadUrl"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-success="handleSuccess"
:before-remove="beforeRemove"
:before-upload="beforeAvatarUpload"
multiple
:limit="10"
:on-exceed="handleExceed"
:file-list="fileList"
:on-change="handleChange"
>
<el-button size="small" type="primary">点击上传</el-button>
<!-- <div slot="tip" class="el-upload__tip">
只能上传jpg/png文件,且不超过500kb
</div> -->
</el-upload>
</el-form-item>
data(){
return{
// 如果用action直接上传,走接口,那么需要拼接api
uploadUrl: process.env.VUE_APP_BASE_API + "/file/uploadFile",
}
}
//删除方法
handleRemove(file, fileList) {
let _this = this;
delFile(file.id).then((res) => {
//
if (res.code == 200) {
// 手动删除fileList中的当前文件--el-upload并不能手动fileList中的数据
var _tmp = _this.fileList;
for (var i = 0, len = _tmp.length; i < len; i++) {
if ((_tmp[i].name = file.name)) {
_tmp.splice(i, 1);
break;
}
}
_this.fileList = _tmp;
}
});
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
},
// handleExceed 限制文件个数
handleExceed(files, fileList) {
this.$message.warning(
`当前限制选择 10 个文件,本次选择了 ${files.length} 个文件,共选择了 ${
files.length + fileList.length
} 个文件`
);
},
//删除文件前的提示
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`);
},
//
handleChange(file, fileList) {
},
// 添加成功后依然需要在fileList中添加数据
handleSuccess(response, file, fileList) {
file.response.name = file.name;
this.fileList.push(file.response);
},
//上传前的校验
beforeAvatarUpload(file) {
const isLt50M = file.size / 1024 / 1024 < 30;
const whatType = file.name.substring(file.name.lastIndexOf(".") + 1);
if (
["excel", "word", "pdf", "jpg", "png", "xls", "docx"].indexOf(
whatType
) == -1
) {
this.$message.error(
"上传文件只能是 excel、word、pdf、jpg、png、xls、docx 格式!"
);
this.fileList = this.fileList.slice(-1);
return false;
}
if (!isLt50M) {
this.$message.error("上传文件大小不能超过 30MB!");
return false;
}
return true;
},
如果需要自己控制上传、那么需要这样写,加上 :http-request,
:http-request覆盖默认的上传行为,可以自定义上传的实现
:on-success, :on-error指令不会触发
<el-upload
:action='#'
:http-request='handleSubmit'
</el-upload>
handleSubmit(){
const file = params.file;
// 使用FormData传参数和文件
var form = new FormData();
// 文件
form.append("file", file);
// 参数
form.append("id", this.urlId);
// 调用封装好的上传方法,传给后台FormData
this.uploadFileRequest("/upload/file",form).then(res=>{
if(res && res.status == 200){
this.$message("成功了");
}
auto-upload可以控制是否在选取文件后立即进行上传