通过HTTP方式上传文件

前言

前端发起请求给A项目,A后台接收到MultipartFile类型的请求参数。
然后,A后台需要通过B项目暴露的http接口,将该文件上传至B项目。

步骤

1.引入相关依赖

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
      <version>4.8.1</version>
</dependency>
<dependency>
     <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
     <version>2.6</version>
</dependency>

2.文件写入临时目录

后面通过http方式上传时,需要传入文件的绝对路径。而MultipartFile貌似不能直接获取到,所以需要先将文件写入本地临时目录。

   public File getTmpFile(MultipartFile file){
        //文件先写入本地临时目录
        long curTime = System.currentTimeMillis();
        String pathName = "/tmp/jar/" + curTime + "/";
        File tmpFile = new File(pathName  + file.getOriginalFilename());
        try (InputStream in = file.getInputStream()) {
        	//commons-io包的工具类FileUtils 
            FileUtils.copyInputStreamToFile(in, tmpFile);
        } catch (IOException e) {
            throw new GlobalException("文件写入临时目录失败,原因:" + e.getMessage());
        }
        return tmpFile;
    }

3.通过http上传

核心代码如下

OkHttpClient client = new OkHttpClient().newBuilder().build();
okhttp3.RequestBody body = new MultipartBody.Builder()
				.setType(MultipartBody.FORM)
				//tmpFile.getName=文件名
                .addFormDataPart("file", tmpFile.getName()),
				okhttp3.RequestBody.create(MediaType.parse("application/octet-stream"), 
				//tmpFile.getAbsolutePath()=文件绝对路径
				new File(tmpFile.getAbsolutePath())))
                .build();
Request request = new Request.Builder()
		//上传的http地址
        .url("B项目接口地址")
        .method("POST", body)
        //自定义header
        .addHeader("token", "")
        .build();

Response response = client.newCall(request).execute();
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值