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

文章目录

  • 1.获取到Java SDK
  • 2.在配置类中填写参数
  • 3.Oss配置类
  • 4.代码具体实现
  • 5.接口测试

1.获取到Java SDK

  1. 到阿里云对象存储的SDK下载,选择Java SDK
使用Java SDK上传图片到阿里云对象存储OSS_第1张图片
  1. 查看SDK文档,选择简单上传

使用Java SDK上传图片到阿里云对象存储OSS_第2张图片

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

使用Java SDK上传图片到阿里云对象存储OSS_第3张图片

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

2.在配置类中填写参数

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

​ 点击Bucket实例概览

使用Java SDK上传图片到阿里云对象存储OSS_第4张图片

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

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

使用Java SDK上传图片到阿里云对象存储OSS_第5张图片

​ 点击创建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;
    }
}

4.代码具体实现

  1. 加入阿里云OSS对象存储依赖

<dependency>
    <groupId>com.aliyun.ossgroupId>
    <artifactId>aliyun-sdk-ossartifactId>
    <version>3.10.2version>
dependency>
  1. Controller层
@RestController
public class UploadController {

    @Resource
    private UploadService uploadService;

    @PostMapping("/upload")
    public ResponseResult uploadImg(MultipartFile img){
       return uploadService.uploadImg(img);
    }
}
  1. Service层接口
public interface UploadService {
    ResponseResult uploadImg(MultipartFile img);
}
  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;
    }
}

5.接口测试

  1. 采用ApiFox发送请求

使用Java SDK上传图片到阿里云对象存储OSS_第6张图片

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

使用Java SDK上传图片到阿里云对象存储OSS_第7张图片

  1. 前端项目测试

    上传成功

使用Java SDK上传图片到阿里云对象存储OSS_第8张图片

你可能感兴趣的:(SpringBoot,Java,java,阿里云,开发语言)