Springmvc 上傳文件 ,文件名中文亂碼。spring
spring 編碼過濾器,tomcat,請求頁面的編碼都是utf-8,但接收到的中文文件名仍是變成亂碼了。tomcat
最後懷疑是 CommonsMultipartResolver編碼問題,用如下方式查看後,都是utf-8
public class MyMultipartResolver extends CommonsMultipartResolver {
private static final Log log = LogFactory.getLog(MyMultipartResolver.class);
//fileItem.getContentType() >request.getCharacterEncoding()> FileUpload().getHeaderEncoding > WebUtils.DEFAULT_CHARACTER_ENCODING
//表單元素的編碼規則:fileItem.getContentType() > determineEncoding(request) = request.getCharacterEncoding()> FileUpload().getHeaderEncoding > WebUtils.DEFAULT_CHARACTER_ENCODING
@Override
protected String determineEncoding(HttpServletRequest request) {
String encoding = request.getCharacterEncoding();
log.debug(" request.getCharacterEncoding --->" + encoding );
if (encoding == null) {
encoding = getDefaultEncoding();
log.debug(" getDefaultEncoding --->" + encoding );
}
return encoding ;
}
// CUSTOM Encoding
@Override
protected String getDefaultEncoding() {
String encoding = getFileUpload().getHeaderEncoding();
log.debug(" getFileUpload().getHeaderEncoding --->" + encoding );
if (encoding == null) {
encoding = WebUtils.DEFAULT_CHARACTER_ENCODING;
log.debug(" WebUtils.DEFAULT_CHARACTER_ENCODING --->" + encoding );
}
return encoding;
}
@SuppressWarnings("unchecked")
protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
String encoding = determineEncoding(request);
log.debug(" determineEncoding --->" + encoding );
FileUpload fileUpload = prepareFileUpload(encoding);
try {
List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
return parseFileItems(fileItems, encoding);
}
catch (FileUploadBase.SizeLimitExceededException ex) {
throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
}
catch (FileUploadException ex) {
throw new MultipartException("Could not parse multipart servlet request", ex);
}
}
protected FileUpload prepareFileUpload(String encoding) {
FileUpload fileUpload = getFileUpload();
FileUpload actualFileUpload = fileUpload;
// Use new temporary FileUpload instance if the request specifies
// its own encoding that does not match the default encoding.
if (encoding != null && !encoding.equals(fileUpload.getHeaderEncoding())) {
actualFileUpload = newFileUpload(getFileItemFactory());
actualFileUpload.setSizeMax(fileUpload.getSizeMax());
actualFileUpload.setHeaderEncoding(encoding);
}
log.debug(" actualFileUpload HeaderEncoding--->" + actualFileUpload.getHeaderEncoding() );
return actualFileUpload;
}
} mvc
最終看到了這個:ide
HttpEntity entity = MultipartEntityBuilder.create()ui
.setMode(HttpMultipartMode.RFC6532)//BROWSER_COMPATIBLE自定義charset,RFC6532=utf-8,STRICT=iso-8859-1編碼
.addTextBody("name", testFile, textUtf8)//中文文件名仍是須要傳utf-8編碼spa
.addBinaryBody("file", new File(testFile))debug
.build();ip
只有用這個HttpMultipartMode.RFC6532上傳纔是對的。utf-8