【问题标题】:CSV download for rest API not workingREST API 的 CSV 下载不起作用
【发布时间】:2017-01-25 08:34:24
【问题描述】:

我正在尝试通过将数据写入响应输出流来下载 csv。我已将内容配置设置为 text/csv 、 application/octet-stream、 openxml、 ms-excel.Tried ,包括接受标头。 还尝试了 Response Builder 来构建 bytearrayoutputstream。

甚至在本地创建了一个文件并尝试下载。

但是,我在响应正文中收到了 csv 响应。下载没有发生,没有提示下载。我正在使用 RESTEASY JAXRS。

@POST
@Path("/response")
@Produces({"application/vnd.ms-excel"})
@Consumes({MediaType.APPLICATION_JSON})
public void viewSomething(PolicyRequest input,@Context HttpServletResponse responseExcel){

    try
    {
        List<List<String>> data= getData(something)
        String filename =   "sample.csv";

        responseExcel.addHeader("Content-Disposition", "attachment;filename="+filename);    
        responseExcel.addHeader("Content-Type" ,"application/vnd.ms-excel");


        OutputStreamWriter osw = new OutputStreamWriter(responseExcel.getOutputStream());
        CSVWriter writer = new CSVWriter(osw);

        for(List<String> rows : data){
            String[] row = rows.toArray(new String[0]);
            writer.writeNext(row);
        }
writer.flush();
writer.close();
osw.close();                    
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    }

【问题讨论】:

    标签: rest csv response resteasy content-disposition


    【解决方案1】:

    您返回了错误的 Content-Type 标头:@Produces({"application/vnd.ms-excel"})

    应该是@Produces({"text/csv"})

    同样显式设置标题应该是过时的,因为 @Produces 会为你做这件事

    【讨论】:

      猜你喜欢
      • 2020-01-21
      • 2023-03-04
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 2021-03-05
      • 2016-03-27
      • 2018-01-29
      • 2016-12-21
      相关资源
      最近更新 更多