Spring REST - 正在下载损坏/空白文件

时间:2018-04-26 12:14:59

标签: java spring spring-boot postman

我正在尝试创建一个端点来呈现/提供PDF文件。 我已经通过以下链接来构建API,但仍面临一些问题。

link 1

link 2

以下是我的代码:

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文件,但问题是它完全是空白的。可能是什么问题?

2 个答案:

答案 0 :(得分:1)

多种方式从服务器下载文件,您可以使用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浏览器读取数据,这意味着它是并行的。

@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);
            }
        };
    }

答案 1 :(得分:0)

您可以尝试使用apache commons IOUtils。为什么重新发明轮子:) 1.打开与远程服务器的连接 2.将inputStream复制到目标文件outputStream。

public void downloadFileFromRemoteLocation(String serverlocation, File destinationFile) throws IOException
{
    try (FileOutputStream fos = new FileOutputStream( destinationFile )){
        URL url = new URL(serverlocation);
        URLConnection connection = url.openConnection();
        IOUtils.copy( connection.getInputStream(),  fos);
    } 
}

如果你想坚持使用Java,那么请看下面的代码片段

try {
        // Get the directory and iterate them to get file by file...
        File file = new File(fileName);

        if (!file.exists()) {
            context.addMessage(new ErrorMessage("msg.file.notdownloaded"));
            context.setForwardName("failure");
        } else {
            response.setContentType("APPLICATION/DOWNLOAD");
            response.setHeader("Content-Disposition", "attachment"+ 
                                     "filename=" + file.getName());
            stream = new FileInputStream(file);
            response.setContentLength(stream.available());
            OutputStream os = response.getOutputStream();      
            os.close();
            response.flushBuffer();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }