项目场景:
项目中需要上传文件(pdf,txt...),照片等是就可以用到el-upload
描述
我有个项目中用到el-upload自带的上传文件的方式,但是出现了token丢失的问题,所以改成了自定义的一种上传方式,我对el-upload的两种上传方式做个简单的回顾:
默认上传方式:通过 action 和 on-success 等
自定义:通过 http-request ,覆盖默认的上传,自定义为表单形式上传
方法一(默认):
<el-upload
ref="importUploader"
class="upload-demo"
:action="uploadUrl"
:data="{
conferenceId: $route.query.conferenceId,
noticeId: $route.query.noticeId,
officeCode: $route.query.officeCode,
}"
:headers="headerData"
accept=".xlsx"
:multiple="false"
:limit="1"
:on-success="onSuccessed"
:on-error="onErrored"
:on-change="onChange"
:before-upload="beforeUpload"
:auto-upload="false"
>
<el-button size="small" type="primary">选择文件</el-button>
<span>{{
this.exitFilename ? this.exitFilename : "未选择任何文件"
}}</span>
<div slot="tip" class="el-upload__tip">
<div class="tips">温馨提示:请导入“xlsx”格式文件!</div>
</div>
</el-upload>
data:
uploadUrl:this.$config.VUE_APP_API_HOST_DEFAULT +"/接口url",
computed: {
headerData() {
return Object.assign(
{},
{
Authorization: getAccessToken(),
timestamp: String(new Date().getTime()),
sign: "",
}
);
},
},
方法:
onSuccessed(response, file, fileList) {
if (response && response.code === 200 && response.data) {
//导入成功
}
else {
this.$message({
type: "error",
message: response.data.result,
dangerouslyUseHTMLString: true,
});
}
},
onErrored(err, file, fileList) {
this.$message({
type: "error",
message: "导入失败",
dangerouslyUseHTMLString: true,
});
},
onChange(file) {
this.exitFilename = file.name;
},
beforeUpload(file) {
const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
const whiteList = ["xls", "xlsx"];
if (whiteList.indexOf(fileSuffix) === -1) {
this.$message.error("上传文件格式不正确");
this.exitFilename = "";
return false;
}
},
1.参数及方法:
action:上传的url ,data:接口需要的数据,headers:请求头的token信息,on-success:上传成功后的回调函数,beforeUpload文件上传前的文件类型校验
2.分析:
这种方式的请求不走封装的公共axios的请求,header请求信息,及返回的信息处理等都需要来自行配置,使用简单
方法二(自定义http-request):
<el-upload
ref="importUploader"
class="upload-demo"
:action="/"
:http-request="handleImport"
accept=".xlsx"
:multiple="false"
:limit="1"
:before-upload="beforeUpload"
:auto-upload="false"
>
<el-button size="small" type="primary">选择文件</el-button>
<span>{{
this.exitFilename ? this.exitFilename : "未选择任何文件"
}}</span>
<div slot="tip" class="el-upload__tip">
<div class="tips">温馨提示:请导入“xlsx”格式文件!</div>
</div>
</el-upload>
方法
//封装axios请求
import request from '@/utils/request'
handleImport(params) {
let formData = new FormData();
formData.append("file", params.file)
//file额外的参数也需要append进去
formData.append('conferenceId',this.$route.query.conferenceId);
formData.append('noticeId',this.$route.query.noticeId);
formData.append('officeCode',this.$route.query.officeCode);
request({
url: 'url',
method: 'post',
headers: {
'Content-Type': 'multipart/form-data'
},
data: formData
}).then((response) => {
//成功的处理
}).catch((response)=> {
}).finally(() => {
});
},
分析:
优点:这是自定义成表单的形式上送文件,可以使用全局axios处理之后的请求方式,不用再处理header和返回状态这些
缺点:全局封装的报错信息等的不统一,需要自己单独看着不想提示的处理一下,还有el-upload上传除了file之外的参数时,需要跟file一样,append到formdata中上送