OkHttp 通过post请求上传文件
【摘要】 一、添加pom 依赖
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp --><dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</...
一、添加pom 依赖
-
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
-
<dependency>
-
<groupId>com.squareup.okhttp3</groupId>
-
<artifactId>okhttp</artifactId>
-
<version>3.10.0</version>
-
</dependency>
二、上产文件接口编写
-
@ApiOperation("上传文件(移动云)")
-
@PostMapping("/uploadFileToOos")
-
public ResultJson uploadFileToOos(@RequestParam("file") MultipartFile file) throws IOException {
-
String fileName = file.getOriginalFilename();
-
File sendFile = new File("/tmp/tmp-" + fileName + "");
-
try {
-
file.transferTo(sendFile);
-
OkHttpClient httpClient = new OkHttpClient();
-
MediaType mediaType = okhttp3.MediaType.parse(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE);
-
-
String policy = "{ \"expiration\": \"" + OosCommonUtil.getExpireTime() + "\",\n" +
-
" \"conditions\": [\n" +
-
" {\"bucket\": \"" + haimen_bucket + "\" },\n" +
-
"{\"key\":\"" + fileName + "\"}" +
-
" ]\n" +
-
"}";
-
-
RequestBody fileBody = RequestBody.create(mediaType, sendFile);
-
String base64Policy = OosCommonUtil.getBase64Policy(policy);
-
-
String signature = OosCommonUtil.signWithHmacSha1(secretAccessKey, base64Policy);
-
-
RequestBody requestBody = new MultipartBody.Builder().
-
setType(MultipartBody.FORM)
-
.addFormDataPart("key", fileName)
-
.addFormDataPart("AccessKeyId", accessKeyId)
-
.addFormDataPart("policy", base64Policy)
-
.addFormDataPart("signature", signature)
-
.addFormDataPart("file", fileName, fileBody).build();
-
-
Request request = new Request.Builder()
-
.post(requestBody)
-
.url(obsUri)
-
.addHeader("Date", OosCommonUtil.getObsHeaderDate(System.currentTimeMillis()))
-
.addHeader("Host", host)
-
.addHeader("Content-Type", org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE)
-
.addHeader("Origin", origin)
-
.build();
-
-
Response response = httpClient.newCall(request).execute();
-
if (response != null) {
-
if (response.code() == 204) {
-
AliOssResponse aliOssResponse = new AliOssResponse();
-
aliOssResponse.setSize(file.getSize());
-
aliOssResponse.setUrl(obsUri + "/" + fileName);
-
return ResultJson.getInstance().setData(aliOssResponse).setCode(200).setMsg("success");
-
} else {
-
return ResultJson.getInstance().setData(null).setCode(200).setMsg("error");
-
}
-
}
-
return ResultJson.getInstance().setData(null).setCode(200).setMsg("error");
-
} finally {
-
if (sendFile.exists()) {
-
sendFile.delete();
-
}
-
}
-
}
文章来源: blog.csdn.net,作者:血煞风雨城2018,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/qq_31905135/article/details/90369100
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)