Skip to content

Instantly share code, notes, and snippets.

@alexstolr
Created August 13, 2019 07:02
Show Gist options
  • Save alexstolr/e37d9b266de4d0dfcb84a05070c0fcf8 to your computer and use it in GitHub Desktop.
Save alexstolr/e37d9b266de4d0dfcb84a05070c0fcf8 to your computer and use it in GitHub Desktop.
stream multiple files via REST
-------
server:
-------
@Controller
@Slf4j
public class FileController {
@GetMapping(value = "/files")
public void getFiles(HttpServletResponse response){
List<String> fileNames = Arrays.asList("file1.csv","file2.csv");
response.addHeader("FileNames", "file1.csv;file2.csv");
fileNames.forEach( fileName -> {
try {
InputStream inputstream = new FileInputStream(fileName);
IOUtils.copy(inputstream, response.getOutputStream());
inputstream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
------------------------------------------------------------------------------------------------------
-------
client:
-------
public class FileStreamingService {
public void getFiles(){
String url = "http://localhost:" + "7000" + "/files";
RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);
restTemplate.setRequestFactory(requestFactory);
restTemplate.execute(url, HttpMethod.GET, null, clientHttpResponse -> {
String fileNamesCombined = clientHttpResponse.getHeaders().getFirst("FileNames");
List<String> FileNames = new ArrayList<>(Arrays.asList(fileNamesCombined.split(";")));
List<File> files = new ArrayList<>();
FileNames.forEach( fileName -> files.add(new File(fileName)));
files.forEach(file ->{
try {
FileOutputStream outputStream = new FileOutputStream(file);
InputStream inputStream = clientHttpResponse.getBody();
int byteCount = 0;
byte[] buffer = new byte[4096];
int bytesRead;
int bytesAllowed = 892/2; // CHANGE THIS ACCORDING TO YOUR NEEDS
while(bytesAllowed > 0 && inputStream.available() > 0){
bytesRead = inputStream.read(buffer,0,bytesAllowed);
outputStream.write(buffer, 0, bytesRead);
bytesAllowed = bytesAllowed - bytesRead;
}
} catch (IOException e) {
e.printStackTrace();
}
});
return "";
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment