• 使用Java SDK上传图片到阿里云对象存储OSS


    该文章已同步收录到我的博客网站,欢迎浏览我的博客网站,xhang’s blog

    1.获取到Java SDK

    1. 到阿里云对象存储的SDK下载,选择Java SDK
    image-20221110104644192
    1. 查看SDK文档,选择简单上传

    image-20221110104939626

    1. 选择上传文件流,获取到源码

    更改源码步骤详见 4.测试 单元

    2.在配置类中填写参数

    # 阿里云OSS对象存储
    oss:
      #  配置地域节点Endpoint
      endpoint: https://oss-cn-shanghai.aliyuncs.com
      accessKeyId: LTAI5tMp**************
      accessKeySecret: TWrV2y************
      bucketName: ************
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    1. 地域节点endpoint获取方式:

    ​ 点击Bucket实例概览

    image-20221110105604856

    1. 访问密钥ID accessKeyId和访问密钥accessKeySecret

    ​ 在头像的位置,点击AccessKey管理,生成对应的accessKeyId和accessKeySecret

    image-20221110105800991

    ​ 点击创建AccessKey

    image-20221110105917425

    1. bucketName即创建的Bucket名

    3.Oss配置类

    此配置类是为了读取application.yaml配置文件当中的OSS参数

    采用@Value的方式读取配置文件当中的OSS参数

    @Component
    public class OssUtils implements InitializingBean {
    
        //读取配置文件中的内容
        @Value("${oss.endpoint}") //属性注解,能将括号中的值注入到属性中去
        private String endpoint;
    
        @Value("${oss.accessKeyId}")
        private String accessKeyId;
    
        @Value("${oss.accessKeySecret}")
        private String accessKeySecret;
    
        @Value("${oss.bucketname}")
        private String bucketName;
    
    
        public static String END_POINT;
        public static String ACCESS_KEY_ID;
        public static String ACCESS_KEY_SECRET;
        public static String BUCKET_NAME;
    
        public void afterPropertiesSet() throws Exception {
            END_POINT = endpoint;
            ACCESS_KEY_ID = accessKeyId;
            ACCESS_KEY_SECRET = accessKeySecret;
            BUCKET_NAME = bucketName;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    4.代码具体实现

    1. 加入阿里云OSS对象存储依赖
    
    <dependency>
        <groupId>com.aliyun.ossgroupId>
        <artifactId>aliyun-sdk-ossartifactId>
        <version>3.10.2version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    1. Controller层
    @RestController
    public class UploadController {
    
        @Resource
        private UploadService uploadService;
    
        @PostMapping("/upload")
        public ResponseResult uploadImg(MultipartFile img){
           return uploadService.uploadImg(img);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    1. Service层接口
    public interface UploadService {
        ResponseResult uploadImg(MultipartFile img);
    }
    
    • 1
    • 2
    • 3
    1. Service层实现类

    ​ 说明objectName是上传到BUCKET_NAME中(即Bucket)文件的路径和文件名

    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.ObjectMetadata;
    import com.xha.domain.ResponseResult;
    import com.xha.service.UploadService;
    import com.xha.utils.ImgUtils;
    import com.xha.utils.OssUtils;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    
    @Service
    public class UploadServiceImpl implements UploadService {
    
        /**
         * 文件上传阿里云OSS
         *
         * @param imgFile
         * @return
         */
        @Override
        public ResponseResult uploadImg(MultipartFile imgFile) {
    //        1.获取到原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            String fileName = ImgUtils.generateFilePath(originalFilename);
            String imgUrl = ossUpload(imgFile, fileName);
            return ResponseResult.okResult(imgUrl);
        }
    
    
        private String ossUpload(MultipartFile multipartFile, String fileName) {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder()
                    .build(OssUtils.END_POINT, OssUtils.ACCESS_KEY_ID, OssUtils.ACCESS_KEY_SECRET);
    
    
            // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
            String objectName = "文件目录/" + fileName;
            try {
    
                InputStream inputStream = multipartFile.getInputStream();
                // 创建PutObject请求。
                ossClient.putObject(OssUtils.BUCKET_NAME, objectName, inputStream);
            } 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());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
    //        返回对象存储中的图片路径        
            return "https://" + OssUtils.BUCKET_NAME + "." + OssUtils.END_POINT + "/" + objectName;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71

    5.接口测试

    1. 采用ApiFox发送请求

    image-20221110132413685

    文件列表中已经存在了上传的图片

    image-20221110132446505

    1. 前端项目测试

      上传成功

    GIF 2022-11-10 13-27-53
  • 相关阅读:
    从零搭建基于SpringCloud Alibaba 鉴权中心服务(详细教程)
    1.6 线程池原理与实战
    【愚公系列】华为云系列之DevCloud+ECS+MySQL搭建超级冷笑话网站【开发者专属集市】
    spark ui 指南
    k8s day04
    vue的学习
    ROS1云课→14可视化交互
    前端开发与后端开发:探索编程世界的两个街区
    动手捣鼓一个log打印调试模块
    个人IPO模式
  • 原文地址:https://blog.csdn.net/qq_52030824/article/details/127787082