前后端分离(Vue+SpringBoot)实现下载功能
后端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | @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) { } } } } |
前端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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对象 }}) } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下