本文旨在解决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/n/375603.html