java实现从服务器下载文件浏览器上

tech2022-12-12  103

// response 会以流的形式响应到浏览器上 path文件地址 protected void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> parameterMap = getParameterMap(request); String resourceId =(String)parameterMap.get("resourceId"); String depId =(String)parameterMap.get("depId"); ResourceDto resourceDto = resourceService.getByResourceId(resourceId); String path=resourceDto.getOutterIp()+resourceDto.getOriginPath(); log.info("下载地址:{}",path); log.info("下载文件名称: {}",resourceDto.getResourceName()); if (null == path ) { throw new RuntimeException("remoteFileUrl is invalid!"); } this.buildDownloadRecord(depId,resourceId); URL url = new URL(path); BufferedInputStream in = null; in = new BufferedInputStream(url.openStream()); response.reset(); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(resourceDto.getResourceName(), "UTF-8") + "\""); // 将网络输入流转换为输出流 try { int i; while ((i = in.read()) != -1) { response.getOutputStream().write(i); } } catch (IOException e) { log.error("下载文件有误:{}",e); } finally { in.close(); response.getOutputStream().close(); } }
最新回复(0)