文件上传下载格式化方法
1、上传
<input
ref="showinput2"
v-show="false"
type="file"
@change="upFile()"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
name=""
id="file" />
/**
* - accept属性限制文件 PDF DOC DOCX
* - accept: application/pdf,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document
*/
const pollutionUpload = data => {
return http({
url: `api/pollution/upload`,
data,
method: 'post',
//请求头设置类型
headers: { 'Content-Type': 'multipart/form-data' },
});
};
const $this = this;
const fileData = document.getElementById('file').files[0];
const params = new FormData();
const NameNode = `${this.pollutionText()}导入模板`;
const [filesName1] = this.filesName.split('.');
console.log(NameNode, this.filesName.split('.')[0]);
params.append('categoryId', this.pollutionTypeId);
params.append('file', fileData);
dataImport(params)
.then(res => {
console.log(res);
$this.filesName = '';
$this.BatchImportFlag = false;
$this.reset();
const obj = document.getElementById('file');
// 清空input框选中文件值
obj.value = '';
})
.catch(err => {
console.log(err);
});
// 文件过大预览PDF副本 特殊化60秒
const lisenseCopyPdf = data => {
return http({
url: `api/pollution/source/lisense/copy/${data}`,
method: 'get',
responseType: 'blob',
timeout: 20000 * 3,
});
};
let blob;
lisenseCopyPdf(data).then(res => {
blob = res;
})
// FileReader主要用于将文件内容读入内存
const reader = new FileReader();
reader.readAsDataURL(blob);
// onload当读取操作成功完成时调用
reader.onload = e => {
const a = document.createElement('a');
// 获取文件名fileName pdf下载
// let fileName = res.headers['content-disposition'].split('=');
// fileName = fileName[fileName.length - 1];
// fileName = fileName.replace(/"/g, '');
a.download = 'fileName.pdf';
a.href = e.target.result;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
// pdf iframe预览
const res = await api();
$this.iframPageUrl = '';
const data = res.data;
let fileName = `正本.pdf`;
if ($this.iframeShowOne) {
fileName = `副本.pdf`;
}
const blob = new Blob([data], {
type: 'application/pdf;charset=utf-8',
});
/* 兼容ie内核,360浏览器的兼容模式 */
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
/* 火狐谷歌的文件下载方式 */
const href = window.URL.createObjectURL(blob);
$this.iframPageUr = href;
$this.showFlag = false;
}
// const url = URL.createObjectURL(new Blob([res]));
// const link = document.createElement('a');
// excel下载
// const fileName = `${new Date().getTime()}.xlsx`;
// link.style.display = 'none';
// link.href = url;
// link.setAttribute('download', fileName);
// document.body.appendChild(link);
// link.cilck();
// document.body.removeChild(link);