1、responseType设置为:arraybuffer
2、Blob设置type,来源于后台封装的response.headers[‘content-type’]
3、使用encodeURIComponent(),避免符号影响文件名
function previewFile(file) {
let newName = file.fileNewName
let filePath = file.filePath
let path = filePath+newName
let encodedFileName = encodeURIComponent(path)
const lowerCaseFileName = newName.toLowerCase();
const fileExtension = lowerCaseFileName.split('.').pop();
const allowedExtensions = ['pdf', 'jpg', 'jpeg', 'png'];
if (allowedExtensions.includes(fileExtension)) {
let service = axios.create({
baseURL: '/fjxz',
responseType: 'arraybuffer',
timeout: 60000,
headers: {
'Content-Type': 'application/octet-stream',
},
withCredentials: true,
});
service.get(`/system/fileupload/preview/file?filePath=${filePath + newName}`)
.then((response) => {
console.log(response)
let contentType = response.headers['content-type'];
let blob = new Blob([response.data], {
type: contentType
});
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.target = "_blank";
link.click();
})
.catch((error) => { })
} else {
ElMessage({
message: '只有PDF和图片才能预览!',
type: 'warning',
})
}
}