java httpclient 文件_java使用HttpClient上传文件并使用SpringMVC接收文件

来到医鸣的第一篇博客~~~

本文分享的是使用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 "上传成功";

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值