问题描述
elmentUI 中的upload默认的提交行为是通过action
属性中输入的url链接,提交到指定的服务器上。但是这种url提交文件的方式,在实际的项目环境中往往是不可取的。我们的服务器会拦截所有的请求,进行权限控制,密钥检查,请求头分析等安全行为控制。写在这里的url无法实现定义请求参数之类的,就更不能进行后面的操作了。如果你说放行这个请求不就行了嘛,确实,放行不做任何操作是可以,真被人攻击了,到时候定责的时候就麻烦了。所以最恰当的方式,就是自定义文件的上传行为。
实现讲解
为了方便讲解,我这里将
auto-upload
属性设置为false,需要手动提交文件上传。
el-upload中有一个属性http-request
,官方的描述是说 覆盖默认的上传行为,可以自定义上传的实现,类型是function,可选值与默认值都省略。经过我的探索,我发现它可以接收一个参数,这个参数保存了你文件上传的对象。绑定的方法,会在【文件上传】事件触发后再触发。比如说,你先选择文件,点击【上传】按钮,触发上传事件,才会触发到http-request
中绑定的函数。建议绑定的方法为同步方法,原因后面会讲到。
实现步骤
先定义了一个 el-upload
标签,在里面先把自动上传文件关闭,由于action
是必填项,所以就塞了个#进去,在http-request
中绑定了我自定义的handleFileUpload
函数。在这个函数里面,我实现了自定义文件上传的请求。里面的button,用来上传文件的。
<el-upload
action="#"
ref="upload"
:show-file-list="false"
:auto-upload="false"
:http-request="handleFileUpload"
>
<el-button
size="small"
type="primary"
@click="submitUpload"
>Import</el-button>
</el-upload>
点击提交按钮,将el-upload中的内容提交,此时会转入到handleFileUpload
函数中,执行自定义文件上传的函数。
async submitUpload() {
this.fileDataLoading = true;
this.$refs.upload.submit();
},
来到handleFileUpload
函数中,用xhr接收文件上传对象。新建一个FormData对象,将数据封装到FormData中并提交到服务器,这和你在页面新建一个表单,然后提交表单是同一样的。
async handleFileUpload(fileObject) {
let fd = new FormData(); // 新建一个FormData()对象,这就相当于你新建了一个表单
fd.append("file", fileObject.file); // 将文件保存到formData对象中
fd.append("serverType", this.importServerType) // 这是我其他数据,你需要的话,也可以添加
try {
// TestUploadGw中的uploadFile方法,实际上是使用了 axios
// 在这里,我手动提交了一个表单数据,并接收返回值。
let res = (await TestUploadGw.uploadFile(fd)).data;
if (res.result === STATUSES.SUCCESS) {
this.$message({
message: "Import file successfully! ",
type: "success",
});
// 赋值
this.fileData = res.data;
} else {
this.$message.error({
message: res.message,
});
this.fileName = "";
}
} catch (error) {
this.$message.error("Import file failed! ");
this.$refs.upload.clearFiles();
} finally {
this.fileDataLoading = false;
}
},
如果你很好奇 xhr 里面接收了什么样的数据,可以看看这里
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-I4E6pvyv-1638778836499)(C:\Users\YANGAL7\AppData\Roaming\Typora\typora-user-images\image-20211206145016920.png)]
但其实,上面的这段代码是有问题的。我的res能接收到返回值,console.log()也能打印出来,但是页面渲染数据却是 No Data. 其实是因为,http-request
中绑定的函数无法进行同步操作,如果你的函数是异步的,它会在你提交上传时,就先把它放到一边去了,你不知道它什么时候才会真的帮你上传,回传的数据是有,但是就是没办法渲染出来了,$forceUpdate() 也不行。如果你不需要返回值,那问题不大。
那用promise行不行?
答案是肯定的,promise不用声明异步函数(async),所以会等待它文件上传执行完成之后渲染数据
handleFileUpload(fileObject) {
this.beforeImport = false;
let fd = new FormData();
fd.append("file", fileObject.file);
fd.append("serverType", this.importServerType);
TestUploadGw.uploadFile(fd).then((uploadRes) => {
let res = uploadRes.data;
if (res.result === STATUSES.SUCCESS) {
this.$message({
message: "Import file successfully! ",
type: "success",
});
this.fileData = res.data;
} else {
this.$message.error({
message: res.message,
});
this.fileName = "";
}
this.$refs.multipleTable.toggleAllSelection();
}).catch((error) => {
this.$message.error("Import file failed! ");
this.$refs.upload.clearFiles();
}).finally(() => {
this.fileDataLoading = false;
});
},
这个流程是最完整、最合理的,点击提交按钮,提交数据,然后执行自定义的上传文件函数。除此之后,还有一个方法。如果你们开发团队不能用promise函数(避免回调地狱),强制使用async & await,那这个时候,其实还有一个办法。
你可以在http-request
绑定的函数中只获取需要上传的文件,在提交el-upload的方法中,去上传文件并获取返回值。这样子也可以实现,并没有什么不妥,不过,只是读代码的人,感觉你写的位置不太合理,提交函数就应该做提交的事,上传函数就应该干上传的事。
提交函数
async submitUpload() {
this.fileDataLoading = true;
this.$refs.upload.submit();
let fd = new FormData(); // 新建一个FormData()对象,这就相当于你新建了一个表单
fd.append("file", this.file); // 将文件保存到formData对象中
fd.append("serverType", this.importServerType) // 这是我其他数据,你需要的话,也可以添加
try {
// TestUploadGw中的uploadFile方法,实际上是使用了 axios
// 在这里,我手动提交了一个表单数据,并接收返回值。
let res = (await TestUploadGw.uploadFile(fd)).data;
if (res.result === STATUSES.SUCCESS) {
this.$message({
message: "Import file successfully! ",
type: "success",
});
// 赋值
this.fileData = res.data;
} else {
this.$message.error({
message: res.message,
});
this.fileName = "";
}
} catch (error) {
this.$message.error("Import file failed! ");
this.$refs.upload.clearFiles();
} finally {
this.fileDataLoading = false;
}
}
上传函数
handleFileUpload(fileObject) {
this.file = fileObject.file;
}
我个人喜欢用promise这种,见仁见智吧。