下载网络文件,地址是 http://sk.sit.fosuntech.cn/group1/M00/00/72/CqYKHVn69wyAMl6YAAVf953sp4Y075.pdf
前端调用下载链接
function downloadAttachement(imageId, fileName) { var url = _HTTP_IP_PORT + 'repayment/downloadAttachment.do?imageId=' + imageId + '&fileName=' + fileName; var form = $("<form></form>").attr("action", url).attr("method", "post"); form.appendTo('body').submit().remove(); }
后台用的spring,接受请求参数
@ RequestMapping(value = "/repayment/downloadAttachment", method = RequestMethod.POST) @ ResponseBody public String downloadAttachment(String imageId, String fileName, HttpServletRequest request, HttpServletResponse response) { if (StringUtils.isEmpty(imageId)) { throw new CommonException("影像ID不能为空!"); } if (StringUtils.isEmpty(fileName)) { throw new CommonException("文件名不能为空!"); } //这里获取的下载链接 http://sk.sit.fosuntech.cn/group1/M00/00/72/CqYKHVn69wyAMl6YAAVf953sp4Y075.pdf String downLoadPath = templateService.getDownloanUrl(imageId); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //如果不存在乱码的情况可以忽略,由于请求参数文件名为中文,到后台会乱码,考虑操作系统和客户端浏览器默认编码 //判断服务器操作系统,本地开发使用windows String os = System.getProperty("os.name"); if (os.toLowerCase().indexOf("windows") != -1) { fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1"); } else { //判断浏览器 String userAgent = request.getHeader("User-Agent").toLowerCase(); if (userAgent.indexOf("msie") > 0) { fileName = URLEncoder.encode(fileName, "ISO-8859-1"); } } //响应二进制流 response.setContentType("application/octet-stream"); response.reset(); //清除response中的缓存 //根据网络文件地址创建URL URL url = new URL(downLoadPath); //获取此路径的连接 URLConnection conn = url.openConnection(); Long fileLength = conn.getContentLengthLong(); //获取文件大小 //设置reponse响应头,真实文件名重命名,就是在这里设置,设置编码 response.setHeader("Content-Disposition", "attachment; filename=" + fileName); response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(conn.getInputStream()); //构造读取流 bos = new BufferedOutputStream(response.getOutputStream()); //构造输出流 byte[]buff = new byte[1024]; int bytesRead; //每次读取缓存大小的流,写到输出流 while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } response.flushBuffer(); //将所有的读取的流返回给客户端 } catch (IOException e) { logger.error("文件下载失败!", e); throw new CommonException("文件下载失败!"); } finally { try { if (null != bis) { bis.close(); } if (null != bos) { bos.close(); } } catch (IOException e) { logger.error("文件下载失败!", e); throw new CommonException("文件下载失败!"); } } return null; }
原文链接:https://blog.csdn.net/wu8439512/article/details/78481479
文章评论