发表评论
来到医鸣的第一篇博客~~~
本文分享的是使用HttpClient上传文件并在服务端使用SpringMVC接收文件
1、需要的jar包:
commons-httpclient-3.1.jar
commons-codec-1.9.jar
commons-lang-2.5.jar
2、上传代码
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"); //********业务处理 } } catch (Exception ex) { ex.printStackTrace(); } finally { postMethod.releaseConnection(); } }
3、服务端接收代码
/** * 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){ if(file == null){ return "没收接收到文件"; } try { OutputStream out = new FileOutputStream(new File("/home/demo/")); // 保存图片 FileCopyUtils是Spring自带的工具类 FileCopyUtils.copy(file.getInputStream(), out); } catch (Exception e) { e.printStackTrace(); return "报错咯"; } return "上传成功"; }