前置条件 AccessKey
引入依赖
都是官网上的:https://help.aliyun.com/zh/oss/developer-reference/java-installation?spm=a2c4g.11186623.0.i16
<!--若是创建项目的时候这个依赖勾选了就不用了--><!--不加启动会报错No active profile set, falling back to 1 default profile: "default"--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--引入OSS--><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.15.1</version></dependency><!--如果使用的是Java 9及以上的版本,则需要添加JAXB相关依赖。添加JAXB相关依赖示例代码如下:--><dependency><groupId>javax.xml.bind</groupId><artifactId>jaxb-api</artifactId><version>2.3.1</version></dependency><dependency><groupId>javax.activation</groupId><artifactId>activation</artifactId><version>1.1.1</version></dependency><!-- no more than 2.3.3--><dependency><groupId>org.glassfish.jaxb</groupId><artifactId>jaxb-runtime</artifactId><version>2.3.3</version></dependency>
创建 Bucket
官网手动创建
代码创建–下面的 AliOssUtils 有这块内容
public static String buckName(String bucketName) throws Exception {// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。//EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();//这里不使用上述方法 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);// 填写Bucket名称,例如 upload-bucket-test-cao。Bucket名称在OSS范围内必须全局唯一。//String bucketName = "upload-bucket-test-cao";try {// 创建存储空间。ossClient.createBucket(bucketName);//删除存储空间。//ossClient.deleteBucket(bucketName);} catch (OSSException oe) {System.out.println("Host ID:" + oe.getHostId());} catch (ClientException ce) {System.out.println("Error Message:" + ce.getMessage());} finally {if (ossClient != null) {ossClient.shutdown();}}return bucketName+"成功";}
封装工具类 AliOssUtils
package com.dudu.upload;import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;import java.io.InputStream;/*** @Author dudu* @Description AliyunUtils* @Date 2024-05-07 12:30* @Version 1.0*/
public class AliOssUtils {// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。private static final String ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com";private static final String ACCESS_KEY_ID = "xxxxxxxxxxxxxx";private static final String ACCESS_KEY_SECRET = "xxxxxxxxxxxxxxxxxxxx";private static final String BUCKETNAME = "5-2-upload-bucket";public static String upLoadFile(String objectName, InputStream in) throws Exception {String url = "";// 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);try {// 创建PutObjectRequest对象。PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, objectName, in);// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。// ObjectMetadata metadata = new ObjectMetadata();// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());// metadata.setObjectAcl(CannedAccessControlList.Private);// putObjectRequest.setMetadata(metadata);// 上传字符串。PutObjectResult result = ossClient.putObject(putObjectRequest);url="https://"+BUCKETNAME+"."+ENDPOINT.substring(ENDPOINT.lastIndexOf("/")+1)+"/"+objectName;} 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 (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();}}return url;}/*** @param bucketName* @return* @throws Exception*/public static String buckName(String bucketName) throws Exception {// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。//EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();//这里不使用上述方法 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);// 填写Bucket名称,例如 upload-bucket-test-cao。Bucket名称在OSS范围内必须全局唯一。//String bucketName = "upload-bucket-test-cao";try {// 创建存储空间。ossClient.createBucket(bucketName);//删除存储空间。//ossClient.deleteBucket(bucketName);} 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 (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();}}return bucketName+"成功";}
}
调用
@PostMapping("upload")public String upload(MultipartFile file) throws Exception {//创建bucketName//String buckName = AliOssUtils.buckName("5-2-upload-bucket");//System.out.println("buckName = " + buckName);//获取文件名String originalFilename = file.getOriginalFilename();//设置唯一的文件名assert originalFilename != null;String newFileName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));return AliOssUtils.upLoadFile("upload/"+newFileName, file.getInputStream());}
设置文件上传大小限制
spring:servlet:multipart:# 设置上传文件的最大值max-file-size: 10MB
其他操作查看官网
https://help.aliyun.com/zh/oss/getting-started/sdk-quick-start?spm=a2c4g.11186623.0.0.7eae59d4ES6hok#section-yxk-n1d-zei