下载文件Safari

时间:2017-02-27 18:57:44

标签: javascript java spring spring-mvc 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设置为内联而非附件。为什么会这样?

我做错了什么?

3 个答案:

答案 0 :(得分:1)

这不会编译,它只代表你应该做的事情。

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。 我是新手,所以如果这是不好的做法,请通知我。

答案 1 :(得分:1)

尝试不使用float和使用@ResponseBody

答案 2 :(得分:0)

我的服务放在路由模块(这是所有微服务的代理)后面。问题出在这个模块(代理)中,它覆盖了微应用程序服务的头文件和cookie。

按照问题中的描述设置代码就可以了。