我正在制作接收文件下载请求的 Spring Boot Web 服务。
此服务的域是,a.com
并且此服务从b.com
域中带来请求的文件。
此服务需要从外部域请求文件。
我想知道在这种情况下如何向客户端返回文件下载请求的响应。
下面的代码是我制作的。
@RequestMapping(path = "/downloadFile", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {
String testFileName = "https://www.google.co.jp/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
URL url = new URL(testFileName);
File file = new File(url.getFile());
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
}
但由于文件路径,它不起作用。它的路径是这样显示的。
/Users/user/devel/acomapplication/https:/www.google.co.jp/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png
您需要使用 HTTP 客户端下载要代理的文件。下面是一些如何做到这一点的示例。此示例使用 Apache HTTP 客户端 4.5。
@RequestMapping(path = "/downloadFile", method = RequestMethod.GET)
public ResponseEntity download(String param) throws IOException {
String testFileName = "https://www.google.co.jp/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(testFileName);
request.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
request.setHeader("Pragma", "no-cache");
request.setHeader("Expires", "0");
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode()==200) {
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(response.getEntity().getContent());
} else {
return ResponseEntity.notFound();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句