前言
前端发起请求给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();