Bad encoding of streamed CSV with Stripes / Tomcat

我只是一个虾纸丫 提交于 2019-12-24 09:38:54

问题


Actually i'm trying to stream a CSV file. I set the encoding to windows-1252 but it seems it is still streamed as UTF-8 file.

   final String encoding = "windows-1252";
   exportResolution = new StreamingResolution(builder.getContentType() + ";charset=" + encoding.toLowerCase()) {
        @Override
        public void stream(HttpServletResponse response) throws Exception {
            // Set response headers
            response.setHeader("Cache-control", "private, max-age=0");
            response.setCharacterEncoding(encoding);
            OutputStream os = response.getOutputStream();
            writeExportStream(os,builder);
        }
    }.setFilename(filename);

writeExportStream just streams the content to the outputstream (with pagination and db calls, it takes some time)

It doesn't work in local (jetty plugin) + dev (tomcat) Neither with firefox / chrome

I've not tested but people at work told me that it works better when we don't stream the content but we write the file in one time after having loaded all the objets we want from db.

Anybody know what is happening? Thanks

Btw my headers:

HTTP/1.1 200 OK
Content-Language: fr-FR
Content-Type: text/csv;charset=windows-1252
Content-Disposition: attachment;filename="export_rshop_01-02-11.csv"
Cache-Control: private, max-age=0
Transfer-Encoding: chunked
Server: Jetty(6.1.14)

I want the file to be able to be imported in excel in windows-1252 but i can't, it just open in utf8 while my header is windows-1252


回答1:


The problem lies in the writeExportStream(os,builder); method. We can't see what encoding operations it is performing, but I'm guessing it is writing UTF-8 data.


The output operation needs to perform two encoding tasks:

  1. Tell the client what encoding the response text is in (via the headers)
  2. Encode the data writen to the client in a matching encoding (e.g. via a writer)

Step 1 is being done correctly. Step 2 is probably the source of the error.

If you use the provided writer, it will encode character data in the appropriate response encoding.

If pre-encoded data is written via the raw byte stream (getOutputStream()), you need to make sure this process uses the same encoding.



来源:https://stackoverflow.com/questions/4865208/bad-encoding-of-streamed-csv-with-stripes-tomcat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!