HttpPost实现上传文件(File类)

MultipartFile 转 File
public static File multipartFileToFile(MultipartFile file) throws Exception {

   File toFile = null;
   if (file.equals("") || file.getSize() <= 0) {
      file = null;
   } else {
      InputStream ins = null;
      ins = file.getInputStream();
      toFile = new File(file.getOriginalFilename());
      inputStreamToFile(ins, toFile);
      ins.close();
   }
   return toFile;
}

@GetMapping("/test")
public R test(@RequestParam("file") MultipartFile file) throws Exception {

   String body = null;
   FileBody bin = null;
   StringBuilder res = new StringBuilder();
   Map returnMap = new HashMap();
   CloseableHttpClient client = HttpClients.createDefault();
   HttpPost post = new HttpPost("http://127.0.0.1:8555/file/upload/-1");
   if(file != null) {
      bin = new FileBody(multipartFileToFile(file));
   }
   MultipartEntity reqEntity = new MultipartEntity();
   reqEntity.addPart("file", bin);
   post.setHeader("authorization","Bearer d437cc17-8841-490b-a5d3-ed54827f3c8b");
   post.setEntity(reqEntity);
   CloseableHttpResponse response = client.execute(post);
   HttpEntity entity = response.getEntity();
   try (InputStream is = entity.getContent()) {
      RequestConfig config = RequestConfig.custom().setConnectTimeout(3000).build();
      post.setConfig(config);
      BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
      while ((body = br.readLine()) != null) {
         res.append(body);
      }
      returnMap = (Map) JSON.parse(res.toString());
      System.out.println(returnMap);
   } catch (Exception var14) {
      var14.printStackTrace();
   }

   return R.ok();
}

来自httpclient通过POST来上传文件,而不是通过流的形式,并在服务端进行解析(通过httpmime.jar来操作)_linwei_1029的专栏-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值