前后端分离(Vue+SpringBoot)实现下载功能
作者:互联网
后端:
@GetMapping("/down") public void fileinfo(String path,HttpServletRequest request, HttpServletResponse response) { // 其余处理略 InputStream inputStream = null; OutputStream outputStream = null; try { File file = new File(path); if(!file.exists()){ response.setStatus(404); throw new RuntimeException("文件不存在.."); } response.setContentType("application/force-download");// 设置强制下载不打开 response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1")); inputStream = new BufferedInputStream(new FileInputStream(path)); outputStream = response.getOutputStream(); byte[] buf = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, len); } response.flushBuffer(); } catch (IOException e) { response.setStatus(404); e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { } } } }
前端:
down(path,fileName){ this.$api.fileinfo.down(path,fileName).then(res => { if (!res || res.size === 0) { Vue.prototype['$message'].warning('文件下载失败') return } if (typeof window.navigator.msSaveBlob !== 'undefined') { window.navigator.msSaveBlob(new Blob([res.data]), fileName) } else { let url = window.URL.createObjectURL(new Blob([res.data])) var aLink = document.createElement("a"); aLink.style.display = "none"; aLink.href = url; aLink.setAttribute("download", fileName); document.body.appendChild(aLink); aLink.click(); document.body.removeChild(aLink); //下载完成移除元素 window.URL.revokeObjectURL(url); //释放掉blob对象 }}) }
标签:Vue,SpringBoot,aLink,res,fileName,outputStream,new,response,下载 来源: https://www.cnblogs.com/magic-wong/p/15842027.html