java下载文件流,不生成中间文件。
- 代码设计:
- 代码实现
代码设计:
从前端获取的数据经过后端加工后,生成文件流,并返回前端,(不生成中间文件,注意内存,记得关闭流)
代码实现
@ApiOperation(value = "下载文件", notes = "")@PostMapping("/getDownLoadScriptFile")public void getDownLoadScriptFile(@RequestBody ParamsObject vo, HttpServletRequest request, HttpServletResponse response) throws Exception {SysUserEntityVo uc = (SysUserEntityVo) request.getAttribute("UC");gClientScriptService.getDownLoadScriptFile(vo, uc,response);}
@Overridepublic void getDownLoadScriptFile(ParamsObject vo, SysUserEntityVo uc, HttpServletResponse response) throws Exception {String fileContent = vo.getFileContent();String fileName = vo.getFileName();String encodeFileName = URLEncoder.encode(fileName);ServletOutputStream out = response.getOutputStream();try {//设置允许跨域的keyresponse.setHeader("Access-Control-Expose-Headers", "Content-Disposition");//文件名有“,”等特殊字符发送到前端会报错,用""括起来解决response.addHeader("Content-Disposition", "attachment;filename=\"" + encodeFileName + "\"");//设置文件大小response.addHeader("Content-Length", "" + fileContent.getBytes().length);//设置文件名,避免问题,这个也用""括起来response.setHeader("filename,", "filename=\"" + encodeFileName + "\"");//设置文件类型response.setContentType("application/octet-stream");out.write(fileContent.getBytes(StandardCharsets.UTF_8));out.flush();} catch (Exception e) {throw e;} finally {try {out.close();} catch (Exception e) {throw e;}try {out.close();} catch (Exception e) {throw e;}}}