本文旨在解決vue下載無後綴名的文件被加上後綴.txt,有後綴名的文件下載正常的問題,提供完整的代碼示例供參考。
一、分析問題
首先,需了解vue中下載文件的情況。一般情況下,我們都是使用http協議進行文件下載,但是當使用get請求時,瀏覽器默認會將文件後綴名加上.txt,導致下載下的文件無法正常打開。而使用post請求時則不會出現此問題。
二、解決方法
為了解決此問題,我們需要對下載文件的請求進行處理,強制讓瀏覽器以二進制方式打開文件。
1、前端代碼
// 綁定下載事件 async downloadFile(item) { const res = await axios({ method: 'get', url: item.url, responseType: 'blob', }); const fileName = decodeURI(res.headers['content-disposition'].split('=')[1]); const link = document.createElement('a'); const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' }); link.href = URL.createObjectURL(blob); link.download = fileName; link.click(); },
2、後端代碼
@RequestMapping(value = "/download") @ResponseBody public ResponseEntity<ByteArrayResource> download(HttpServletRequest request, HttpServletResponse response) throws IOException { byte[] data = null; // 設置響應頭,通知瀏覽器以二進制流方式下載文件 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); // 讀取文件 File file = new File(filePath); FileInputStream input = new FileInputStream(file); data = new byte[(int) file.length()]; input.read(data); input.close(); return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(data), HttpStatus.OK); }
三、總結
以上就是解決vue下載無後綴名的文件被加上後綴.txt,有後綴名的文件下載正常問題的解決方法。通過前後端的代碼處理,讓瀏覽器以二進制流方式打開下載的文件,再通過設置響應頭告訴瀏覽器以附件形式下載文件,就可以正常下載和打開文件了。
原創文章,作者:ASIMU,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/375603.html