1、上传代码:
public void httpClient(File file,String s1,String s2) {
String url = UPLOAD_URL;
long startTime = System.currentTimeMillis();
PostMethod postMethod = new PostMethod(url);
try {
Part[] parts = { new FilePart("file", file), new StringPart("fileName", "file"),
new StringPart("s1", s1) ,new StringPart("s2", s2,"UTF-8")};
MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
postMethod.setRequestEntity(mre);
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);
//请求
int status = client.executeMethod(postMethod);
//结束时间
long endTime = System.currentTimeMillis();
if (status == HttpStatus.SC_OK) {
byte[] responseBody = postMethod.getResponseBody();
String responseStr = new String(responseBody,"utf-8");
System.out.println(responseStr);
//********业务处理
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
postMethod.releaseConnection();
}
}
2、服务端接收代码
/**
* PictureEntity 图片相关实体类 包括上传端传递的fileName/s1/s2等
* @param file 接收到的文件
* @param vo
* @param request
* @return
*/
@RequestMapping(value="http://www.zhangc.cn/zb_users/uploadimage.do",method=RequestMethod.POST)
@ResponseBody
public String uploadImage(@RequestParam(value = "file", required = false) MultipartFile file,
PatientTempEntity vo,HttpServletRequest request){
JSONObject json = new JSONObject();
if(file == null){
json.put("data", "未接收到文件");
json.put("code", "failed");
json.put("url", "");
return JSON.toJSONString(json);
}
try {
OutputStream out = new FileOutputStream(new File("/home/demo/"));
// 保存图片 FileCopyUtils是Spring自带的工具类
FileCopyUtils.copy(file.getInputStream(), out);
json.put("data", "上传成功");
json.put("code", "success");
json.put("url", "");
} catch (Exception e) {
e.printStackTrace();
json.put("data", e.getMessage());
json.put("code", "failed");
json.put("url", "");
}
return return JSON.toJSONString(json);
}