Sending a file with Czech characters UTF-8 encoded in filename (Žluťoučký kůň.txt), consumed by RESTEasy. But in java i always become US-ASCII filename (with is wrong of course)
HTML used to send file:
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>
With is really sending:
------WebKitFormBoundaryAyBqNu6jIFHAB660
Content-Disposition: form-data; name="file"; filename="Žluťoučký kůň.txt"
Content-Type: text/plain
Used filters for obtain UTF-8 encoding:
@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 code to read multipart:
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
and header contain:
form-data; name="file"; filename="??lu??ou??k?? k????.txt"
i use wildfly 9 with resteasy. The code above result in class cast exception for me. The code below solve my problem:
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.