Is there a difference between a returned byte array or servlet output stream when loading a file

I am wondering if there is a real difference when the Sprin MVC controller method returns an array of bytes byte[]to represent the downloaded file or when I copy an object InputStreamto an object ServletOutputStream?

The reason I'm asking is because I have to make sure that when downloading large files there will be no OutOfMemory errors. Does the transfer file ask ServletOutputStreamme to avoid it?

Byte array transfer:

byte[] download() {
    return getUrlContentAsByteArray();
}

Pass in ServletOutputStream:

void download(HttpServletResponse response) {
    InputStream content = getUrlContentAsStream();
    ServletOutputStream outputStream = response.getOutputStream();
    response.reset();response.setContentType(ContentType.APPLICATION_OCTET_STREAM.getMimeType());
    IOUtils.copyLarge(inputStream, outputStream);
}
+4
source share
1 answer

. , .

, IOUtils.copy, . IOUtils 4 . Spring Servlet API.

Spring MVC, API , InputStream, , Spring :

@RequestMapping(value = "/download", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Resource> download() {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

    InputStream is = null; // get your input stream here
    Resource resource = new InputStreamResource(is);

    return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
+2

Source: https://habr.com/ru/post/1694293/


All Articles