免費做網(wǎng)站的軟件小廣告設(shè)計
java下載文件流,不生成中間文件。
- 代碼設(shè)計:
- 代碼實現(xiàn)
代碼設(shè)計:
從前端獲取的數(shù)據(jù)經(jīng)過后端加工后,生成文件流,并返回前端,(不生成中間文件,注意內(nèi)存,記得關(guān)閉流)
代碼實現(xiàn)
@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 {//設(shè)置允許跨域的keyresponse.setHeader("Access-Control-Expose-Headers", "Content-Disposition");//文件名有“,”等特殊字符發(fā)送到前端會報錯,用""括起來解決response.addHeader("Content-Disposition", "attachment;filename=\"" + encodeFileName + "\"");//設(shè)置文件大小response.addHeader("Content-Length", "" + fileContent.getBytes().length);//設(shè)置文件名,避免問題,這個也用""括起來response.setHeader("filename,", "filename=\"" + encodeFileName + "\"");//設(shè)置文件類型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;}}}