猿问

如何返回外部域中的文件?(弹簧靴/ java)

我正在制作接收文件下载请求的 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



素胚勾勒不出你
浏览 117回答 2
2回答

慕莱坞森

您需要使用 HTTP 客户端下载您要代理的文件。下面是一些如何做到这一点的示例。此示例使用 Apache HTTP 客户端 4.5。@RequestMapping(path = "/downloadFile", method = RequestMethod.GET)&nbsp;public ResponseEntity download(String param) throws IOException {&nbsp;&nbsp; &nbsp; String testFileName = "https://www.google.co.jp/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"&nbsp;&nbsp; &nbsp; HttpClient client = HttpClientBuilder.create().build();&nbsp; &nbsp; HttpGet request = new HttpGet(testFileName);&nbsp; &nbsp; request.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");&nbsp;&nbsp; &nbsp; request.setHeader("Pragma", "no-cache");&nbsp;&nbsp; &nbsp; request.setHeader("Expires", "0");&nbsp; &nbsp; HttpResponse response = client.execute(request);&nbsp; &nbsp; if (response.getStatusLine().getStatusCode()==200) {&nbsp; &nbsp; ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));&nbsp; &nbsp; return ResponseEntity.ok()&nbsp; &nbsp; &nbsp; &nbsp; .headers(headers)&nbsp; &nbsp; &nbsp; &nbsp; .contentLength(file.length())&nbsp; &nbsp; &nbsp; &nbsp; .contentType(MediaType.parseMediaType("application/octet-stream"))&nbsp; &nbsp; &nbsp; &nbsp; .body(response.getEntity().getContent());&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return ResponseEntity.notFound();&nbsp; &nbsp; }}

回首忆惘然

Path&nbsp;path&nbsp;=&nbsp;Path.resolve(fileName).normalize(); Resource&nbsp;resource&nbsp;=&nbsp;new&nbsp;UrlResource(path.toUri());尝试使用这个。
随时随地看视频慕课网APP

相关分类

Java
我要回答