发送一个以文件名编码的捷克字符UTF-8 (kůň.txt luťoučk)的文件,该文件由RESTEasy消费。但是在java中,我总是变成US文件名(当然,这是错误的)
用于发送文件的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="file";filename=??lu?ou?k? k????.txt“
发布于 2016-08-29 12:32:59
我在resteasy中使用野蝇9。上面的代码为我带来了类强制转换异常。下面的代码解决了我的问题:
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;
}
}https://stackoverflow.com/questions/36008581
复制相似问题