上传下载文件的几种方法

总结Vue开发过程中,上传下载文件的几种方法。

下载

静态资源下载

a标签href指向下载地址,download属性设为空

1
<a href="download.com" download="">下载</a>

动态渲染render函数写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
render: (h, params) => {
let download = h(
'a',
{
attrs: {
href: params.row.filePath,
download: ''
}
},
'下载'
);
return h('div', {}, [download]);
}

arraybuffer转blob

下载excel封装:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function downLoadExcelFile(url, queryString, options = {}) {
if (!api[url]) {
throw new Error(`不存在该下载接口${url}`);
}
let queryOptions = Object.assign({ responseType: 'arraybuffer' }, options);
api[url](queryString, queryOptions).then(({ data, fileName }) => {
let blob = new Blob([data], { type: 'application/vnd.ms-excel' });
let downloadElement = document.createElement('a');
let href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.href = href;
downloadElement.download = 'xxx.xlsx'; //下载后文件名
if (fileName) {
downloadElement.download = fileName;
}
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
});
}

接口调用方法见axios封装及api调用方法

使用:

1
2
3
4
5
6
7
8
9
import { debounce } from '@/utils';

exportTeachers: (function() {
return debounce(function() {
let params = this.searchData;
params.roleId = this.roleId;
this.$download.downLoadExcelFile('schoolContact/exportTeachers', params);
}, 300);
})(),

引入了防抖

新建iframe下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let downloadIFrame = null;
function createDownloadIFrame() {
downloadIFrame = document.createElement('iframe');
downloadIFrame.style.position = 'fixed';
downloadIFrame.style.opacity = '0';
downloadIFrame.style.width = '10px';
downloadIFrame.style.height = '10px';
downloadIFrame.style.left = '-20px';
downloadIFrame.style.top = '-20px';
downloadIFrame.width = '10';
downloadIFrame.height = '10';
document.body.appendChild(downloadIFrame);
}
//下载文件
export function downloadFile(url) {
if (!downloadIFrame) {
createDownloadIFrame();
}
downloadIFrame.src = url ? url : '';
}

取接口给的base64格式小图片

1
2
3
4
this.$api['login/getLoginImages']().then(data => {
let imgEle = document.getElementById('imageMask');
imgEle.setAttribute('src', 'data:image/gif;base64,' + data);
});

上传

formData

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
uploadProofMaterial() {
let formData = new FormData();
formData.append('roleId', this.roleId);
this.fileList.forEach(item => {
formData.append('files', item);
});
formData.append('teacherId', '1');
this.$api['schoolContact/uploadProofMaterial'](formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
timeout: 60000
})
.then(() => {
this.$Message.success('举证材料上传成功!');
this.editSuccessFlag = true;
})
.catch(() => {
this.$Message.error('举证材料上传失败请重试!');
})
}

FormData 接口的append()方法 会添加一个新值到 FormData 对象内的一个已存在的键中,如果键不存在则会添加该键。

1
2
formData.get("k1"); // "v1"
formData.getAll("k1"); // ["v1","v2","v3"]

base64上传小图片

1
2
3
4
<form id="myForm">
<input @change="chooseImage" type="file" accept="image/jpeg,image/x-png,image/gif" id="" value=""/>
</form>
<img id="imageMask" src="">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 选择文件
chooseImage(e) {
this.hasContent = true;
let _this = this;
let contentEl = document.querySelector('#content');
contentEl.focus();
// 读取文件
let files = e.target.files;
let file = files[0];
let reader = new FileReader();
reader.readAsDataURL(file); // 读出 base64
reader.onloadend = function() {
// 图片的 base64 格式, 可以直接当成 img 的 src 属性值
let dataURL = reader.result;
let imgEle = document.getElemetnById('imageMask');
imgEle.setAttribute('src', dataURL);
};
document.getElementById('myForm').reset();
},

参考:发送图文消息