1.使用MultipartFile file接收,不能加requestBody注解
2.file.getOriginalFilename()获取文件名称,file.getInputStream()获取文件流
3.上传oss
public static String putObject(String fileName, InputStream inputStream) {
// 工具类获取值
String endpoint = OssProperties.END_POIND;
String accessKeyId = OssProperties.ACCESS_KEY_ID;
String accessKeySecret = OssProperties.ACCESS_KEY_SECRET;
String bucketName = OssProperties.BUCKET_NAME;
// 创建OSS实例
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建PutObjectRequest对象
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
// 设置该属性可以返回response。如果不设置,则返回的response为空。
putObjectRequest.setProcess("true");
PutObjectResult result = ossClient.putObject(putObjectRequest);
// 如果上传成功,则返回200
if (200 == result.getResponse().getStatusCode()) {
// 把上传之后文件路径返回
// 需要把上传到阿里云oss路径手动拼接出来
return AccouuntConstants.HTTPS_URL + bucketName + AccouuntConstants.DROP + endpoint + AccouuntConstants.BACKSLASH + fileName;
}
} catch (OSSException | ClientException oe) {
log.error("ali oss catch oe:{}", ThrowableUtil.getLastStackTrace(oe, 10));
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return null;
}