亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

素胚勾勒不出你 2021-12-01 19:49:38
我正在制作接收文件下載請求的 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
查看完整描述

2 回答

?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

您需要使用 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();

    }

}


查看完整回答
反對 回復 2021-12-01
?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

Path path = Path.resolve(fileName).normalize();
Resource resource = new UrlResource(path.toUri());

嘗試使用這個。


查看完整回答
反對 回復 2021-12-01
  • 2 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號