争取做到所有的「数据和定义」,都有「来源」。
如: 阿里云 endpoint 的值,来源在最后。
直接看代码
package biz.baijing.utils;
import ...
@Component
public class AliyunOSSFiles {
private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
private String bucketName = "(填写Bucket名称,例如examplebucket)"; // 参见阿里云
private String region = "(填写Bucket所在地域。)北京为例 —— cn-beijing";
private String url;
private String objectName;
public String uploadOSSFile(MultipartFile file) throws ClientException, IOException {
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET
// 环境变量的处理,参考阿里云文档 https://help.aliyun.com/zh/oss/developer-reference/oss-java-configure-access-credentials?spm=a2c4g.11186623.help-menu-31815.d_5_2_1_1_0.23e76d4f2DC3Bb
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 创建OSSClient实例。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 获取上传文件的输入流
InputStream inputStream = file.getInputStream();
// 获得唯一文件名
String ofn = file.getOriginalFilename();
String ext = ofn.substring(ofn.lastIndexOf("."));
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
String dtnow = dateFormat.format(LocalDateTime.now());
// 文件名为 UUID + 当前时间戳 ,分割符为 - ,扩展名为原文件扩展名
objectName = UUID.randomUUID().toString().replace("-","") + '-' + dtnow + ext;
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
// 创建PutObject请求。
PutObjectResult result = ossClient.putObject(putObjectRequest);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (com.aliyun.oss.ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
return url;
}
}
}
阿里云提供了完整的案例,对于配置信息的处理已经是通过配置文件处理了,参考步骤
如何为OSS Java SDK配置访问凭证_对象存储(OSS)-阿里云帮助中心
// Linux 环境
// 第一步
echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
// 第二步
source ~/.bashrc
成功后,查看配置信息是否完成
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRET
对于 URL 的拼接,是在上传文件完成后处理的:
finally {
if (ossClient != null) {
ossClient.shutdown();
}
url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
return url;
}
⚠️ ,以上代码的示例代码是阿里云文档的
如何使用JavaSDK简单上传文件_对象存储(OSS)-阿里云帮助中心
其它类型的上传,根据以上代码的结构能完成修改。
对于文件名的处理部分参考
用 uuid + 当前时间戳构建唯一文件名的上传代码-CSDN博客
⚠️ ,
private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
endpoint 来源 —— 阿里云 OSS 控制台,概况中找到这个部分: