1、阿里云创建OSS功能服务
1、
2、
3、
4、
5、其他的默认
2、相关配置的位置
1、bucketName就是之前创建的Bucket名称。
2、AccessKeyId和AccessSecret位置
3、endpoint可以直接先上传一个文件,然后查看文件的信息
2、编写代码
1、导入依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
2、在application.properties里面写具体信息
#阿里云OSS相关配置
aliyun.oss.file.endpoint=xxx
aliyun.oss.file.accessKeyId=xxx
aliyun.oss.file.accessKeySecret=xxx0iIOU
aliyun.oss.file.bucketname=xxx
3、编写常量配置工具类
@Component
public class ConstOssProperties implements InitializingBean {
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.file.accessKeySecret}")
private String accessKeySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketname;
public static String ENDPOINT;
public static String ACCESSKEYID;
public static String ACCESSKEYSCRET;
public static String BUCKETNAME;
@Override
public void afterPropertiesSet() throws Exception {
ENDPOINT = endpoint;
ACCESSKEYID = accessKeyId;
ACCESSKEYSCRET = accessKeySecret;
BUCKETNAME = bucketname;
}
}
3、编写文件上传工具类
@Override
public String uploadFile(MultipartFile file) {
String endpoint = ConstOssProperties.ENDPOINT;
String accessKeyId = ConstOssProperties.ACCESSKEYID;
String accessKeyScret = ConstOssProperties.ACCESSKEYSCRET;
String bucketName = ConstOssProperties.BUCKETNAME;
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeyScret);
try {
InputStream inputStream = file.getInputStream();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
String dataString = simpleDateFormat.format(date);
String objectName = dataString + "/" + uuid + file.getOriginalFilename();
String fileName = "https://" + bucketName + "." + endpoint + "/" + objectName;
ossClient.putObject(bucketName, objectName, inputStream);
return fileName;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
nally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
|