httpClient上传文件 在Spring MVC中解析文件

文件上传:

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;
 }
 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值