1

发送文件名为捷克文字UTF-8的文件名(Žluťoučkýkůň.txt),由RESTEasy使用。但在Java中,我总是成为US-ASCII文件名(带错了当然)在wildfly上编码文件名multipart/form-data 9

HTML用来发送文件:

Select a file to upload: <br /> 
<form action="http://localhost/file/upload" method="post" enctype="multipart/form-data" accept-charset="UTF-8"> 
    <input type="file" name="file" size="50" /> 

    <input type="submit" value="Upload File" /> 
</form> 

有了真的发送:

------WebKitFormBoundaryAyBqNu6jIFHAB660 
Content-Disposition: form-data; name="file"; filename="Žluťoučký kůň.txt" 
Content-Type: text/plain 

使用的过滤器用于获得UTF-8编码:

@Override 
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) 
     throws IOException, ServletException { 
    servletRequest.setCharacterEncoding("UTF-8"); 

@Override 
    public void filter(ContainerRequestContext requestContext) throws IOException { 
     requestContext.setProperty(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, "*/*; charset=UTF-8"); 
     requestContext.setProperty(InputPart.DEFAULT_CHARSET_PROPERTY, "UTF-8"); 

Java代码来多读:

public List<CaseFile> uploadFile(MultipartFormDataInput input, long caseId) { 
     MultipartFormDataOutput mdo = new MultipartFormDataOutput(); 
    Map<String, List<InputPart>> uploadForm = input.getFormDataMap(); 

    for (List<InputPart> inputParts : uploadForm.values()) { 

     for (InputPart inputPart : inputParts) { 
      try { 

       // Retrieve headers, read the Content-Disposition header to obtain the original name of the file 
       MultivaluedMap<String, String> headers = inputPart.getHeaders(); //here are all headers in US-ASCII 

和报头包含:

形式数据; NAME = “文件”;文件名=“?? lu ?? ou ?? k ?? k ????。txt”

+0

请说明“//这里是US-ASCII中的所有标题”。 –

+0

您如何查看标题?您的输出流可能不支持这些字符。请用UTF-8格式化你的响应,使用h​​ttp://stackoverflow.com/questions/923863/converting-a-string-to-hexadecimal-in-java –

+0

不,我已经试过这样的转换 - 它真的US-ASCII只有 –

回答

0

我用野蛮9与resteasy。上面的代码导致类抛出异常对我来说。下面的代码解决了我的问题:

 Field field = inputPart.getClass().getDeclaredField("bodyPart"); 
     field.setAccessible(true); 
     Object bodyPart = field.get(inputPart); 
     Method methodBodyPart = bodyPart.getClass().getMethod("getHeader", new Class[]{}); 
     Iterable iterable = (Iterable)methodBodyPart.invoke(bodyPart, new Class[]{}); 
     Object[] content = IteratorUtils.toArray(iterable.iterator()); 
     Method methodContent = content[0].getClass().getMethod("getRaw", new Class[]{}); 

     String[] contentDisposition = methodContent.invoke(content[0], new Class[]{}).toString().split(";"); 

     for (String filename : contentDisposition) { 
      if ((filename.trim().startsWith("filename"))) { 

       String[] name = filename.split("="); 

       String finalFileName = name[1].trim().replaceAll("\"", ""); 
       return finalFileName; 
      } 
     }