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();