【SpringBoot后台】整合阿里云OSS实现文件上传

关于OSS的基础使用,可以参看下前面的文章 点击进入,这里主要介绍下SpringBoot怎样操作阿里云OSS实现文件上传。

1 ServiceImpl.java 代码,可参看官方文档 进入

在这里插入图片描述
这个是官方文档中的代码,可以看到这里是实现上传一段文字 : “Hello OSS”

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import java.io.ByteArrayInputStream;

public class Demo {
    
    

    public static void main(String[] args) throws Exception {
    
    
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "examplebucket";
        // 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "exampledir/exampleobject.txt";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
    
    
            String content = "Hello OSS";
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
        } 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();
            }
        }
    }
}
在ServiceImpl中添加统一的身份认证方法

我们参看了官方文档会发现,每个操作OSS的方法都会有以下的身份认证前缀,这个如果每个方法都加上下面的内容,显得代码较冗余。

  // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "examplebucket";

所以我们配置下面的代码段,具体的代码可以参看 之前的文章,该方法可以在Bean初始化后进行加载,当然也可以使用一个简单的 非静态代码块来实现。

//首先定义相关的类全局属性
//存放endpoint地址
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
 //初始化Bean之后需要进行的操作
    @Override
    public void afterPropertiesSet() throws Exception {
    
    
         Endpoint以杭州为例,其它Region请按实际情况填写。
        endpoint = ossEntity.getEndpoint();
         阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
        accessKeyId = ossEntity.getAccessKeyId();
        accessKeySecret = ossEntity.getAccessKeySecret();
        bucketName = ossEntity.getBucketName();
    }
有了以上的定义后,其实可以将 upload 方法写为
public String upload(MultipartFile file){
    
    
        // 填写Object完整路径,例如"avater/test.jpg"。Object完整路径中不能包含Bucket名称。这个路径会在 OSS 后台生成相应的目录和文件
        String objectName = "avater/test.jpg";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
    
    
            //String content = "Hello OSS";
            try{
    
    
                ossClient.putObject(bucketName, objectName, file.getInputStream());
            }catch (IOException iOException){
    
    
                System.out.println("Error Message:" + iOException.getMessage());
            }
            //ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
        } 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 "成功";
    }
编写Controller层测试代码
	@Autowired
	private AliOssService aliOssService;
	@ApiOperation("Oss上传文件")
    @PostMapping("/upload")
    public Result upload(MultipartFile file){
    
    
        String upload= aliOssService.upload(file);
        return Result.ok().message(upload);
    }
发布工程,访问测试

在这里插入图片描述
OSS控制台
在这里插入图片描述
在这里插入图片描述
后台测试成功

猜你喜欢

转载自blog.csdn.net/qq_29750461/article/details/122906314