js + java文件下载
js请求:
// 下载图片 function oDownLoad(url, filename) { var url = '${pageContext.request.contextPath}/file/downFile.do?url=' + url + '&filename=' + encodeURI(filename); window.location.href = url; }
java后端:
@RequestMapping(value = "/downFile.do", method = RequestMethod.GET) public void downPicture(HttpServletRequest request, HttpServletResponse response) throws Exception { InputStream in = null; String url = request.getParameter("url"); String filename = request.getParameter("filename"); //filename = java.net.URLDecoder.decode(filename, "UTF-8"); filename = new String(filename.getBytes("GB2312"),"iso-8859-1"); try { URL httpUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(100000);// 连接超时单位毫秒 // conn.setReadTimeout(200000);// 读取超时 单位毫秒 conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.connect(); in = conn.getInputStream(); byte[] bs = new byte[1024]; int len = 0; response.reset(); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + filename); ServletOutputStream out = response.getOutputStream(); while ((len = in.read(bs))!= -1){ out.write(bs,0,len); } out.flush(); //关流 out.close(); }catch (Exception e){ throw new RuntimeException(url + "下载失败"); }finally { try{ in.close(); }catch (Exception e){ } } }
不积跬步,无以至千里;不积小流,无以成江海。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具