springboot实现下载文件,并且在下载完成删除文件
需求是别人请求我的接口,我的接口调用第三方接口下载文件到我本地,我再把文件给别人。由于我的sdk是把文件保存在本地,我需要保证本地不会有太多的临时文件占用,因此需要下载完成删除文件。
首先我们是不清楚用户下载完成的时间的,但是我们只需要保证把所有数据写入缓冲区后删除文件即可。以下是代码,代码是粗略版,仅供参考。
/** * 下载文件 */ @ApiOperation(value = "下载文件", notes = "下载文件") @PostMapping(value = "/contract/download", produces = "application/json;charset=UTF-8") public void contractDownload(HttpServletResponse response, @RequestBody X2ContractDownloadRequest req) { try { // 获取远程文件 Path filePath = iQiyuesuoSdkService.contractDownload(req); // 设置响应头 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=\"" + filePath.getFileName().toString() + "\""); // 分段下载 int BUFFER_SIZE = 1024 * 100; // 100KB try (FileInputStream fis = new FileInputStream(filePath.toFile()); BufferedInputStream bis = new BufferedInputStream(fis); ServletOutputStream sos = response.getOutputStream()) { byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { sos.write(buffer, 0, bytesRead); } } // 删除文件 Files.delete(filePath.toFile().toPath()); } catch (IOException ex) { ex.printStackTrace(); } }
也可以通过springboot的 ResponseEntity<InputStreamResource>+FileInputStream 重写read方法在读取完成删除文件,只是我没有测试成功,时间原因就先临时解决下。