最近项目中有个模块需要上传多张图片,在传递每个文件的文件名字的时候,服务端收到的中文是乱码,经检查发现双方都是utf-8,各种调试之后,我把问题定位到MultipartEntity的设置上面,最终找到解决方案,就是设置HttpMultipartMode为浏览器兼容模式,即:
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
Charset.forName("UTF-8"));
此外传参时候需要指定编码格式
entity.addPart("fileUploadFileName", new StringBody(file.getName(), Charset.forName("UTF-8")));
下面贴下完整代码:
private String uploadMultiPics(List<String> paths) {
String result = "fail";
String url = AppConfig.URL_WEB + "uploadTaskFile" + AppConfig.URL_ACTION;
try {
BasicHttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 60 * 1000);
HttpConnectionParams.setSoTimeout(params, 60 * 1000);
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
Charset.forName("UTF-8"));
entity.addPart("param.taskId", new StringBody(item.getId()));
for (int i = 0; i < paths.size(); i++) {
File file = new File(paths.get(i));
entity.addPart("fileUpload", new FileBody(file));
entity.addPart("fileUploadFileName", new StringBody(file.getName(), Charset.forName("UTF-8")));
entity.addPart("fileType", new StringBody("png"));
}
post.setEntity(entity);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity responseEntity = response.getEntity();
result = EntityUtils.toString(responseEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}