上传下载功能:
用到的 UI 库为 Antdv 组件库
页面层代码:
<div>
<a-upload
name="file"
accept=".xls,.xlsx" // 接受上传的文件类型
:customRequest="customRequest" // 自定义上传事件,覆盖默认行为
:before-upload="beforeUpload" // 上传前的钩子
:showUploadList="false" // 是否展示 uploadList
>
<a-icon type="upload" :class="['icon-color', textFontSizeMiddle]" /> // 上传的 icon 图标
</a-upload>
<a-icon
type="download"
@click="download" // 下载的图标和方法
:class="['icon-color', textFontSizeMiddle]"
/>
</div>
用到的方法:
beforeUpload(file) {
console.log(file, 'fff');
if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
this.$message.warning('上传的文件类型必须是.xls,.xlsx');
return false;
}
},
customRequest(file) {
this.$message.loading({ content: '正在上传...', key: this.key, duration: 0 });
console.log(file, 'file');
const formData = new FormData();
formData.append('file', file.file);
// 后端提供的接口
uploadFile(formData).then((res) => {
console.log(res);
if (res.status == 200) {
this.$message.success({ content: res.message, key: this.key, duration: 2 });
window.location.reload();
} else {
this.$message.success({ content: res.message, key: this.key, duration: 2 });
}
});
},
// 下载方法
download() {
// 后端提供的接口
downLoad().then((res) => {
console.log(res.data);
const blob = new Blob([res.data]);
// 封装一个保存的插件 可以抽离到utils中
saveFile(blob, '数据更新模板.xlsx');
});
},
utils中封装的保存方法
export function saveFile(data, name) {
try {
const blobUrl = window.URL.createObjectURL(data);
const a = document.createElement('a');
a.style.display = 'none';
a.download = name;
a.href = blobUrl;
a.click();
} catch (e) {
alert('保存文件出错');
}
}