我正在尝试创建一个端点来渲染/提供PDF文件。我已经通过以下链接构建了API,但是仍然面临一些问题。
以下是我的代码:
byte[] targetArray = null; InputStream is = null; InputStream objectData = object.getObjectContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(objectData)); char[] charArray = new char[8 * 1024]; StringBuilder builder = new StringBuilder(); int numCharsRead; while ((numCharsRead = reader.read(charArray, 0, charArray.length)) != -1) { builder.append(charArray, 0, numCharsRead); } reader.close(); objectData.close(); object.close(); targetArray = builder.toString().getBytes(); is = new ByteArrayInputStream(targetArray); return ResponseEntity.ok().contentLength(targetArray.length).contentType(MediaType.APPLICATION_PDF) .cacheControl(CacheControl.noCache()).header("Content-Disposition", "attachment; filename=" + "testing.pdf") .body(new InputStreamResource(is));
当我使用邮递员访问API时,我可以下载PDF文件,但问题是它完全空白。可能是什么问题?
从服务器下载文件的 方法 有 多种 ,可以使用ResponseEntity<InputStreamResource>,。HttpServletResponse以下是两种下载方法。
ResponseEntity<InputStreamResource>
HttpServletResponse
@GetMapping("/download1") public ResponseEntity<InputStreamResource> downloadFile1() throws IOException { File file = new File(FILE_PATH); InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName()) .contentType(MediaType.APPLICATION_PDF).contentLength(file.length()) .body(resource); }
要么
您可以StreamingResponseBody用来下载 大 文件。在这种情况下,服务器同时将数据写入OutputStream浏览器读取的数据,这意味着它是并行的。
StreamingResponseBody
OutputStream
@RequestMapping(value = "downloadFile", method = RequestMethod.GET) public StreamingResponseBody getSteamingFile(HttpServletResponse response) throws IOException { response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=\"demo.pdf\""); InputStream inputStream = new FileInputStream(new File("C:\\demo-file.pdf")); return outputStream -> { int nRead; byte[] data = new byte[1024]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { System.out.println("Writing some bytes.."); outputStream.write(data, 0, nRead); } }; }