Wicket WebResponse附件标题与UTF-8字符?

时间:2015-05-18 15:37:14

标签: encoding utf-8 wicket httpwebresponse

在wicket项目中,我使用请求处理程序进行文件下载。一切都很好,直到我有非标准编码的文件,如utf-8。

我使用此代码生成响应

@Override
   public void respond(IRequestCycle requestCycle)
   {
      WebResponse response = (WebResponse) requestCycle.getResponse();
      response.setAttachmentHeader(briefcaseDocument.getName());
      response.setContentType(briefcaseDocument.getMimeType());
      response.setContentLength(briefcaseDocument.getSize());
      InputStream inputStream = null;
      OutputStream outputStream = null;
      try
      {
         inputStream = briefcaseDocument.getInputStream();
         outputStream = response.getOutputStream();
         IOUtils.copyLarge(inputStream, outputStream);
      }
      catch (Exception e)
      {
         throw new RuntimeException("unable to push file content", e);
      }
      finally
      {
         IOUtils.closeQuietly(inputStream);
         IOUtils.closeQuietly(outputStream);
      }
   }

但如果文档有特殊字符,我会得到空文件名。例如:

ćććć是:

Content-Disposition attachment; filename="   ";

ćwiek是:

Content-Disposition attachment; filename=" wiek";

我读了this堆栈主题并更改了这样的代码:

 String fileName = briefcaseDocument.getName();
 String encoded = URLEncoder
         .encode(briefcaseDocument.getName(), "UTF-8");

 response.setHeader("Content-Disposition","attachment" +
 ((!Strings.isEmpty(fileName)) ? ("; filename=\"" + fileName + "\"; filename*=UTF-8''"+encoded) : "" ));

然后我得到结果:

Content-Disposition attachment; filename="  "; filename*=UTF-8''%C4%87%C5%BC

和文件名表示良好,但我对此解决方案感觉不太好;)如何正确制作wicket设置文件名?

1 个答案:

答案 0 :(得分:3)

根据http://greenbytes.de/tech/tc2231/,这是正确的方法。

自7.0.0-M1(https://issues.apache.org/jira/browse/WICKET-4934)以来,Wicket会自动为您执行此操作。