// 预览文件
preview: function(item) {
var vm = this;
if (!item.raw) {
var itemBasicId = this.form.itemBasicId
var url =ctx + '/aea/item/basic/getItemDocOrTemplateFile.do?itemBasicId='+itemBasicId+'&fileType=applyTableTemplate'
axios({
method: 'GET',
headers: { 'Authorization': 'bearer '+localStorage.getItem("access_token") },
url: url,
originResponse: true,
responseType: 'blob' // 更改responseType类型为 blob
}).then( function(res) {
vm.previewPdfAndPic(res.data)
}).catch(function(err) {
console.log(err)
})
}else{
// vm.openBlobFile(item)
}
},
previewPdfAndPic: function (response) {
var _fileName = '申请表模板.docx', fileType = 'pdf';
if(response.headers['content-disposition']){
var temp = response.headers['content-disposition'];
_fileName = temp.split(';')[1].split('filename=')[1];
fileType = _fileName.substring(_fileName.lastIndexOf('.'));
var fileName = _fileName.substring(0, _fileName.lastIndexOf('.')); // 文件名
}
console.log(fileName)
console.log(fileType)
try {
if(fileType.toLocaleLowerCase === 'pdf'){
// 转换pdf
var blob = new Blob([response], { type: 'application/pdf' });
var url = window.URL.createObjectURL(blob);
var tempwindow=window.open(); // 先打开页面
tempwindow.location= url
}else if(['.png', '.jpg','.jpeg', '.gif'].indexOf(fileType.toLocaleLowerCase) !== -1){
var imgBlob = new window.Blob([response], { type: 'image/png' })
var url = window.URL.createObjectURL(blob);
var tempwindow=window.open(); // 先打开页面
tempwindow.location= url
}else if(['.doc', '.docx'].indexOf(fileType.toLocaleLowerCase) !== -1){
var downloadUrl = window.URL.createObjectURL(new Blob([response], { type: "application/octet-stream" }));
var link = document.createElement('a');
link.style.display = 'none';
link.href = downloadUrl;
link.download = decodeURI(_fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
} catch (error) {
var downloadUrl = window.URL.createObjectURL(new Blob([response], { type: "application/octet-stream" }));
var link = document.createElement('a');
link.style.display = 'none';
link.href = downloadUrl;
link.download = decodeURI(_fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
},
openBlobFile: function (item) {
if(item.raw) {
const tempFileType = item.name.substring(item.name.length - 4)
if (['.pdf', '.PDF'].indexOf(tempFileType) !== -1) {
state.ImgSrc = null
state.PDFURL = window.URL.createObjectURL(props.fileRaw)
openTips.close()
return
}
if (['.png', '.jpg','.jpeg', '.gif'].indexOf(tempFileType) !== -1) {
state.PDFURL = null
const reader = new FileReader();
reader.onload = (evt) => {
state.ImgSrc = evt.target.result
};
reader.readAsDataURL(props.fileRaw);
}
}
},
前端如何获取响应头Content-Disposition中的filename,获取文件类型fileType进行不同类型的文件预览
于 2024-01-05 20:31:41 首次发布
文章介绍了如何使用axios从服务器获取文件,通过content-disposition头判断文件类型,然后针对不同类型的文件(如PDF、图片、Word文档等)进行处理,包括创建URL对象、转换格式和下载。
摘要由CSDN通过智能技术生成