文件上传:
public void testUserInfoSync() throws Exception {
String localFile = "d:/qq.png";
String url = "http://localhost:8080/sync/user_header";
File file = new File(localFile);
PostMethod postMethod = new PostMethod(url);
try {
Part[] parts = {
new FilePart(file.getName(), file),
new StringPart( "fileName" , file.getName()),
new StringPart( "userAccount" , "admin001")
};
MultipartRequestEntity mre = new MultipartRequestEntity(parts,
postMethod.getParams());
postMethod.setRequestEntity(mre);
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);
int status = client.executeMethod(postMethod);
Assert.assertEquals(status, HttpStatus.SC_OK);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
postMethod.releaseConnection();
}
}
文件解析:
@SuppressWarnings("unchecked")
@RequestMapping(value="/user_header",method=RequestMethod.POST)
public Object processUpload(HttpServletRequest request, HttpServletResponse response){
Map<String,Object> paramsMap = new HashMap<String,Object>();
Map<String,Object> returnMap = new LinkedMap();
boolean bool = false;
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//上传文件路径
String uploadPath = this.getUploadPath();
//解析文件信息和请求参数
String fileName = multipartRequest.getParameter("fileName");
String userAccount = multipartRequest.getParameter("userAccount");
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(fileName);
paramsMap.put("userAccount", userAccount);
paramsMap.put("userHeadUrl", "http://ip/"+fileName);
try {
bool = userService.userHeaderSynV1(paramsMap);
if(bool){//头像信息同步成功后,保存头像文件
File dirPath = new File(uploadPath);
if (!dirPath.exists()) {
dirPath.mkdir();
}
try {
File uploadFile = new File(uploadPath+fileName);
FileCopyUtils.copy(file.getBytes(), uploadFile);
} catch (IOException e) {
e.printStackTrace();
}
returnMap.put("status", Constants.Success);
returnMap.put("msg","用户头像同步成功!");
return returnMap;
}
returnMap.put("status", Constants.Fail);
returnMap.put("msg","用户头像同步失败!");
} catch (Exception e1) {
e1.printStackTrace();
}
return returnMap;
}