[英]Java spring file download proxy with rest calls
我需要在 java 中創建一個休息服務,它將依次連接到另一個休息服務以進行文件下載。 現在,我只需要將文件從另一個后端傳輸到客戶端,但將來會進行一些處理/轉換。
對於我項目中的所有 Web 服務,我們使用的是 spring rest(用於提供和使用服務)。
我的問題是考慮到文件很大並且我不想遇到 OutOfMemory 錯誤,什么是合適的方法。
其他一些帖子中的人建議在兩端都使用流,但這真的可能嗎? 為此,我是否需要先將文件寫入磁盤?
我當前的文件下載代碼(消費者)-
public BackendResponse<byte[]> callBackendForFile(BackendRequest request) {
String body = null;
ResponseEntity<byte[]> responseEntity = null;
URI uri = createURI(request);
MultiValueMap<String, String> requestHeaders = getHeadersInfo(request.getHttpRequest());
if (HttpMethod.GET.equals(request.getMethod())) {
responseEntity = restTemplate.exchange(uri, request.getMethod(),
new HttpEntity<String>(body, requestHeaders), byte[].class);
} else {
LOG.error("Method:{} not supported yet", request.getMethod());
}
BackendResponse<byte[]> response = new BackendResponse<>();
response.setResponse(responseEntity);
return response;
}
我的客戶代碼(提供商):
@RequestMapping(value = "/file", method = RequestMethod.GET, produces = "application/xml")
@ResponseBody
public void downloadFileWithoutSpring(HttpMethod method, HttpServletRequest httpRequest,
HttpServletResponse httpResponse) {
BackendRequest request = new BackendRequest(method,
httpRequest.getRequestURI(), httpRequest.getQueryString(), httpRequest);
BackendResponse<byte[]> backendResponse = dutyplanService.getFile(request);
ResponseEntity<byte[]> response = backendResponse.getResponse();
httpResponse.addHeader("Content-Disposition", "attachment; filename=\"" + "attachment.zip" + "\"");
httpResponse.getOutputStream().write(response.getBody());
httpResponse.flushBuffer();
}
注意:上面的代碼無法正常工作,因為下載的附件是一個損壞的文件
我認為只要您從另一台服務器接收到它的 bytearray 內容,您就不需要在服務器上創建該文件。
您可以嘗試將生產注釋的值更改為值application/zip
(或application/octet-stream
,具體取決於目標瀏覽器)而不是“ application/xml
”
你可以直接在 restTemplate 中傳遞HttpServletResponse#getOutputStream()
並寫入它而無需在服務器中保存文件。
public void getFile(HttpServletResponse response) throws IOException {
restTemplate.execute(
"http://ip:port/temp.csv",
HttpMethod.GET,
null,
clientHttpResponse -> {
StreamUtils.copy(clientHttpResponse.getBody(), response.getOutputStream());
return null;
}
);
}
請注意,在調用getFile()
,您應該像這樣關閉 outputStream response.getOutputStream().close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.