簡體   English   中英

下載文件Safari

[英]Download file Safari

我正在嘗試觸發文件下載,但是在Safari上執行此操作時遇到了問題(FireFox和Chrome正常工作)。
這是我的Java代碼:

  @RequestMapping(method = RequestMethod.GET, produces = "text/csv")
  @ResponseBody
  public String getReports(
      final HttpServletResponse response,
      final @RequestParam String data) throws ParseException {
    response.setHeader("Content-type", "text/csv; charset=utf-8");
    response.setHeader("Content-Disposition","attachment; filename='view.csv'");
    String csv = exportCurrentService.extractMatrix(data);
    response.setContentLength(csv.length());

    return csv;
  }

這是我的客戶代碼:

  downloadURI(url, name) {
    const a = document.createElement('a');
    a.href = url;
    a.download = name;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }

在Safari中,響應被打印在屏幕上(加載在同一頁面上)。

注意 :我嘗試了SO上建議的其他方法,但是每種方法都有其自身的問題。

更新:在響應標頭中,我看到Content-Disposition設置為內聯而不是附件。 為什么會這樣呢?

我做錯什么了?

這不會編譯,僅表示您應該執行的操作。

response.setContentType("application/force-download");
response.setContentLength((int)f.length());
        //response.setContentLength(-1);
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\"" + "xxx\"");//fileName);
...
...
File f= new File(fileName);

InputStream in = new FileInputStream(f);
BufferedInputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);

while(din.available() > 0){
    out.print(din.readLine());
    out.print("\n");
    //this is from another answer I saw awhile ago while trying to do the same thing
}

這是我在嘗試執行相同操作時看到的另一篇文章。 原始作者是Vineet Reynolds。 我是新手,所以如果這是不好的做法,請通知我。

嘗試不使用@ResponseBody並使用@ResponseBody produces = MediaType.APPLICATION_JSON_UTF8_VALUE

我的服務位於路由模塊(該路由模塊是所有微服務的代理)的后面。 問題出在這個模塊(代理)中,它正在覆蓋微應用程序服務的標頭和cookie。

按照問題中的描述設置代碼可以解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM