1.文件上传的实现方式
uploadFile(e: any) {
const file = e.target.files[0];
const formData = new FormData();
formData.append("file", file);
instance
.post(url, formData)
.then((res) => {
})
.catch((err) => {
this.$refs.myInput.value = null;
this.$message.error("服务器异常。");
});
}
2.文件下载的实现方式
- 方式一: 前提: encodeURI() 函数可把字符串作为 URI 进行编码。
var a ="张三";
encodeURI(a)// "%E5%BC%A0%E4%B8%89"
decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。
var b = encodeURI("张三");//%E5%BC%A0%E4%B8%89
decodeURI(b) //张三
FileReader.readAsDataURL():读取完成后,result属性将返回一个 Data URL 格式(Base64 编码)的字符串,代表文件内容。对于图片文件,这个字符串可以用于元素的src属性。注意,这个字符串不能直接进行 Base64 解码,必须把前缀data:/;base64,从字符串里删除以后,再进行解码。
下载方法的封装如下
handleDownload() {
axios.post(url, {}, { responseType: "blob" }).then((res: any) => {
var str = res.headers["content-disposition"];
var name = str.split("=")[1].split(".")[0];
var fileType = str.split("=")[1].split(".")[1];
const blob = res.data;
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = (e: any) => {
const a = document.createElement("a");
a.download = decodeURI(name) + "." + fileType;
a.href = e.target.result;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
});
}
- 方式二:
handleDownload() {
const url =
interfaceUrl +
'/upload/download?FileName=' +
'template/' +
decodeURIComponent("“);
window.open(url);
},