文章目录
- 一、 注意事项
- 1、responseType设置为:arraybuffer
- 2、Blob设置type,来源于后台封装的response.headers['content-type']
- 3、使用encodeURIComponent(),避免符号影响文件名
- 二、java接口
一、 注意事项
1、responseType设置为:arraybuffer
2、Blob设置type,来源于后台封装的response.headers[‘content-type’]
3、使用encodeURIComponent(),避免符号影响文件名
function previewFile(file) {let newName = file.fileNewNamelet filePath = file.filePathlet path = filePath+newNamelet 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',})}}
二、java接口
@GetMapping("/preview/file")
public void filePreview(HttpServletResponse response, @RequestParam("filePath") String filePath){try {String extension = getFileExtension(filePath);String mimeType = getMimeType(extension);response.setContentType(mimeType);String encodedFileName = URLEncoder.encode(getFileName(filePath), "UTF-8");response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");FileInputStream fis = new FileInputStream(fileSavePath + filePath);ServletOutputStream os = response.getOutputStream();byte [] b = new byte[1024*8];while(fis.read(b)!=-1){os.write(b);}fis.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
}