【问题标题】:Spring boot rest api csv download don't set file name with extensionSpring boot rest api csv下载不设置带扩展名的文件名
【发布时间】:2020-08-06 13:44:57
【问题描述】:

我正在使用 OpenCSV 库编写用于 CSV 下载的 REST API。我正在设置 Content-Disposition 以使用文件名设置下载。目前,文件已下载但文件名未设置或未设置任何扩展名。它像名为download 一样下载,没有扩展名,但我打开它时数据很好。

在控制器中,我设置了 Content-DispositionContent-Type 以进行响应。

  @GetMapping("/download")
  public void download(HttpServletResponse response) throws IOException {
    response.setContentType("text/csv;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; file=customers.csv");
    service.download(response.getWriter());
  }

这里我在响应写入器中写入 csv 数据。

  public void download(PrintWriter writer) {
    List<Resource> resources = this.getData();
    try (
      CSVWriter csvWriter = new CSVWriter(writer,
                    CSVWriter.DEFAULT_SEPARATOR,
                    CSVWriter.NO_QUOTE_CHARACTER,
                    CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                    CSVWriter.DEFAULT_LINE_END);
    ){
      csvWriter.writeNext(this.getCsvHeader());
      for (Resource resource : resources) {
        csvWriter.writeNext(getCsvData(resource));
      }
    }catch (IOException e) {
      log.info("Writing CSV error {}",e.toString());
      throw new FailedException();
    }
  }

【问题讨论】:

    标签: java spring-boot


    【解决方案1】:

    Content-Disposition 必须使用属性“文件名”

    response.setHeader("Content-Disposition", "attachment; filename=customers.csv");
    

    【讨论】:

    • 不,没关系。也许它会帮助别人。如果它有效,如果您接受我的分析器,我会很高兴
    • 是的,谢谢 Simon Martineli,当我将代码从“附件;文件=客户.csv”更改为“附件;文件名=客户.csv”时,它对我有用
    猜你喜欢
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2023-04-08
    • 2017-02-03
    • 1970-01-01
    相关资源
    最近更新 更多