阿里云对象存储OSS文件上传工具类
使用的依赖包
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.6.2</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.6.0</version>
</dependency>
工具类代码如下
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* @Description 阿里云对象存储上传工具类
* @Author oldwei
* @Date 2019/9/28 12:19
* @Version 2.0
*/
public class AliyunOssUtil {
public Map<String, String> uploadFile(MultipartFile file) {
//上传文件
String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
String uuid = RandomUtil.randomString(32);
// 文件路径
String objectName = "oldweipro/project/" + DateUtil.today() + "/" + uuid + suffix;
// 以下信息在阿里云控制台查找
String accessKeyId = "LTAIJSezLqSmdMkv";
String accessKeySecret = "wUzTRsvGmyrHM8iupefN2G5aFvfwB7";
String bucketName = "atx-hik";
String endpoint = "https://oss-cn-beijing.aliyuncs.com";
String domain = "https://oss.atx.net.cn/";
Map<String, String> map = new HashMap<>(2);
try {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传Byte数组。
byte[] content = file.getBytes();
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));
// 关闭OSSClient。
ossClient.shutdown();
map.put("domain", domain);
map.put("objectName", objectName);
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}