3

I am writing a REST API in a server application that will allow a remote client application to transfer server-client large files. Files that will be sent to about 1-5GB. In addition, it should be resistant to poor transmission and connection. I wrote a service that reads the file and sends it to the client. For small files there is no problem, it has been sent. The problem appeared already at the file about 100mb, because I did not get the answer from http. I tried to read fragment files and only send fragments so that the client application would later be used in full, but the problem of excessive memory usage appears. How do I transfer a file without loading it to the application's memory?

FileInputStream inputStream = new FileInputStream(file2download);
        response.setContentType(URLConnection.guessContentTypeFromName(file2download.getName()));
        response.setContentLength((int) file2download.length());
        String headerValue = String.format("attachment; filename=\"%s\"", file2download.getName());
        response.setHeader("Content-Disposition", headerValue);
        OutputStream outStream = response.getOutputStream();
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = -1; // czytamy w pętli po fragmencie, który następnie przepisujemy do strumienia wyjściowego
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }
        inputStream.close();
        outStream.close();
Amira Bedhiafi
  • 8,088
  • 6
  • 24
  • 60
turo
  • 59
  • 1
  • 9
  • duplicate of https://stackoverflow.com/questions/35680932/download-a-file-from-spring-boot-rest-service – Mick Jul 08 '19 at 11:36
  • 1
    This is not a duplicate because it does not solve the problem of transferring large files. Using an InputStreamResource or ByteArrayResource http response, he only returned 50MB from 1GB and does not ensure the security of losing the server-client connection and resuming the download of part of the file – turo Jul 08 '19 at 13:14
  • I see. Well, ByteArrayResource is a no-go for its need of copying every single byte. InputStreamResource should be a performant solution, but it doesn't allow resuming downloads. For resuming a download, you need to implement the byte-range "Feature". Or Spring needs to. Which version are you using? – Mick Jul 09 '19 at 11:31
  • Spring boot version 2.0.7 RELEASE – turo Jul 09 '19 at 11:45

0 Answers0