引入OSS

前置条件 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

整体视图

在这里插入图片描述

相关推荐

  1. <span style='color:red;'>引入</span><span style='color:red;'>OSS</span>

    引入OSS

    2024-05-09 18:16:11      28 阅读
  2. oss】阿里云oss服务器模拟

    2024-05-09 18:16:11       43 阅读
  3. 记录一下使用 ossfsoss挂载到ecs上

    2024-05-09 18:16:11       62 阅读
  4. 10、将osg的Geometry转换为虚幻引擎的UStaticMesh

    2024-05-09 18:16:11       36 阅读
  5. 9、osg的texture转换为虚幻引擎的UTexture2D

    2024-05-09 18:16:11       122 阅读
  6. OSS 文件下载-Excel

    2024-05-09 18:16:11       34 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-09 18:16:11       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-09 18:16:11       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-09 18:16:11       87 阅读
  4. Python语言-面向对象

    2024-05-09 18:16:11       96 阅读

热门阅读

  1. 可视化卷积网络

    2024-05-09 18:16:11       24 阅读
  2. web server apache tomcat11-32-rewrite

    2024-05-09 18:16:11       37 阅读
  3. C# Solidworks二次开发:枚举应用实战(第十二讲)

    2024-05-09 18:16:11       31 阅读
  4. 学习c#第23天 StringBuilder 效率测试

    2024-05-09 18:16:11       30 阅读
  5. LeetCode 16.最接近的三数之和

    2024-05-09 18:16:11       37 阅读
  6. thinkphp5.1 新建模块

    2024-05-09 18:16:11       31 阅读
  7. C++关联容器unordered_map无法通过索引来访问元素

    2024-05-09 18:16:11       27 阅读
  8. 05. 基于Verilog的呼吸灯程序设计

    2024-05-09 18:16:11       41 阅读