文件下载:
使用封装好的axios 进行文件的下载
export function exportExcel(url: any, name: any, params: any) {
return request({
url: url,
method: "POST",
responseType: "blob",
params: params
})
.then(res => {
console.log(res, '文件');
// 将文件流转成blob形式
const data: any = res
const blob = new Blob([data], { type: "application/vnd.ms-excel" });
const filename = name + ".xls";
const elink = document.createElement("a");
elink.download = filename;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
}
);
}
Bolb格式:new Blob( array, options );
文件上传:
通过input type=file 即可实现文件的上传
实现点击按钮上传文件的操作:
部分代码:
<div class="import" @click="importFunction">
<img src="@/assets/images/dataSharingCenter/import-icon.png" width="16" alt="">
导入
</div>
<input type="file" id="file-btn" @change="selectFile($event)" accept=".xlsx, .xls" style="display: none;" />
// 导入文件
const importFunction = () => {
document.querySelector('#file-btn').click()
}
const selectFile = (e) => {
console.log("🚀 ~ file: index.vue:650 ~ selectFile ~ e:", e.srcElement.files)
const file = e.srcElement.files
var formData = new FormData();
// 将获得文件对象追加到 FormData 对象中
formData.append('file', ...file)
tabFiveTableImport(formData)
.then(res => {
if (res.code === 0) {
ElMessage.success('文件导入成功!')
} else {
ElMessage.error('文件导入失败!')
}
})
}