1 前言
实现在el-upload组件上传文件时,修改文件名再上传到服务器,刚开始是想直接用file.raw.name = 新名称,但是结果报错说file的name是只读属性,不能修改,所以这里使用new File创建新文件,然后整个替换掉raw文件对象。
2 表单上传结构
<el-upload
ref="upload"
class="upload-demo"
:show-file-list="false"
:file-list="fileList1"
action="#"
:headers="headers"
:http-request="handleFileUpload"
>
<el-button
type="primary"
size="small"
style="position: relative; top: -2px; left: 25px"
>上传<i class="el-icon-upload el-icon--right"></i></el-button
>
</el-upload>
(1)使用的是http-request 自定义上传方法,action属性必须有,可任意写个值即可。
(2)使用 :http-request 之后, :on-success, :on-error 指令是不会触发的。
3 封装上传接口(自定义传输请求头,传输格式)
import axios from "axios";
import { getToken } from "@/utils/auth";
export function uploadFileRequest(data) {
return axios({
method: 'post',
url: process.env.VUE_APP_BASE_API + "/businessAdmin/talentsBaseYj/uploadFile",
data: data,
headers: {
'Content-Type': 'multipart/form-data',
Authorization: "Bearer " + getToken(),
}
});
}
4 自定义的上传方法
// 修改时自定义上传方法
handleFileUpload(params){
let newfile=params.file
let suffix = (newfile.name).substr((newfile.name).lastIndexOf("."));
newfile =new File([params.file], `合作协议${suffix}`)
newfile.uid=params.file.uid // new File 没有uid属性,会导致组件底层报错,这里手动加上
console.log(newfile)
// 使用FormData传参数和文件
var form = new FormData();
// 文件
form.append("file", newfile);
// 参数
form.append("id", this.uploadFileId.id);
// 调用封装好的上传方法,传给后台FormData
uploadFileRequest(form).then(res=>{
if(res && res.data.code == 200){
this.$modal.msgSuccess("上传成功");
}
})
},
(1)new File([file.raw],name+'.'+fileType)创建新文件,用来替换原file的raw对象。
(2)new File 没有uid属性,会导致组件底层报错,这里手动加上。