Come on, show! The whole process of SpringBoot OSS integration has not been seen in more detail than this

Preface

Alibaba Cloud Object Storage Service (OSS) is a massive, secure, low-cost, and highly reliable cloud storage service provided by Alibaba Cloud. The data design durability is not less than 99.9999999999% (12 9s), and the service design availability (or business continuity) is not less than 99.995%.

OSS has a platform-independent RESTful API interface. You can store and access any type of data in any application, any time, and any place.

You can use the API, SDK interface, or OSS migration tool provided by Alibaba Cloud to easily move massive amounts of data into or out of Alibaba Cloud OSS. After the data is stored in Alibaba Cloud OSS, you can choose Standard storage as the main storage method for mobile applications, large websites, image sharing, or hot audio and video. You can also choose low-frequency access storage with lower cost and longer storage period ( Infrequent Access) and archive storage (Archive) as storage methods for infrequent access data.

Log in to Alibaba Cloud and enter the console

Click OK and it's built.

  1. Next, start attaching the code,
    create a new springboot project,
    import the dependency  pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>org.example</groupId>
   <artifactId>SpringOOS</artifactId>
   <version>1.0-SNAPSHOT</version>

   <dependencies>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
       <version>2.3.0.RELEASE</version>
   </dependency>

   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-test</artifactId>
       <scope>test</scope>
       <version>2.3.0.RELEASE</version>
   </dependency>

       <!-- OSS SDK 相关依赖 -->
       <dependency>
           <groupId>com.aliyun.oss</groupId>
           <artifactId>aliyun-sdk-oss</artifactId>
           <version>3.4.2</version>
       </dependency>

   <dependency>
       <groupId>org.projectlombok</groupId>
       <artifactId>lombok</artifactId>
       <version>1.18.4</version>
       <scope>provided</scope>
   </dependency>
   <dependency>
       <groupId>joda-time</groupId>
       <artifactId>joda-time</artifactId>
       <version>2.9.9</version>
   </dependency>

   <dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-lang3</artifactId>
       <version>3.8.1</version>
   </dependency>

   </dependencies>
</project>

application.yml

## aliyun oss
## 配置说明参考: com.ljq.demo.springboot.common.config.OSSConfig.class
oss:
   endpoint: oss-cn-shenzhen.aliyuncs.com
   url: https://oos-all.oss-cn-shenzhen.aliyuncs.com/
   accessKeyId: #这里在个人中心里accesskeys查看
   accessKeySecret: #这里在个人中心里accesskeys查看
   bucketName: #这里写OSS里自己创建的OSS文件夹

Write a config configuration class

package com.sykj.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.Serializable;

/**
 * @Description: 阿里云 OSS 配置信息
 * @Author: jiangpengcheng
 * @Date: 2020/07/15
 */
@Data
@Configuration
public class OSSConfig implements Serializable {

    private static final long serialVersionUID = -119396871324982279L;

    /**
     * 阿里云 oss 站点
     */
    @Value("${oss.endpoint}")
    private String endpoint;

    /**
     * 阿里云 oss 资源访问 url
     */
    @Value("${oss.url}")
    private String url;

    /**
     * 阿里云 oss 公钥
     */
    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    /**
     * 阿里云 oss 私钥
     */
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    /**
     * 阿里云 oss 文件根目录
     */
    @Value("${oss.bucketName}")
    private String bucketName;

}

Tools

package com.sykj.util;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.ObjectMetadata;
import com.sykj.config.OSSConfig;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @Description: 阿里云 oss 上传工具类(高依赖版)
 * @Author: @author jiangpengcheng
 * @Date: 2020/7/15
 */

public class OSSBootUtil {

    private OSSBootUtil(){}

    /**
     * oss 工具客户端
     */
    private volatile static OSSClient ossClient = null;

    /**
     * 上传文件至阿里云 OSS
     * 文件上传成功,返回文件完整访问路径
     * 文件上传失败,返回 null
     * @author jiangpengcheng
     * @param ossConfig oss 配置信息
     * @param file 待上传文件
     * @param fileDir 文件保存目录
     * @return oss 中的相对文件路径
     */

    public static String upload(OSSConfig ossConfig, MultipartFile file, String fileDir){
        initOSS(ossConfig);
        StringBuilder fileUrl = new StringBuilder();
        try {
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
            String fileName = System.currentTimeMillis() + "-" + UUID.randomUUID().toString().substring(0,18) + suffix;
            if (!fileDir.endsWith("/")) {
                fileDir = fileDir.concat("/");
            }
            fileUrl = fileUrl.append(fileDir + fileName);
            System.out.println(fileUrl+"-----------------");
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType("image/jpg");

            ossClient.putObject(ossConfig.getBucketName(), fileUrl.toString(), file.getInputStream(),objectMetadata);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        fileUrl = fileUrl.insert(0,ossConfig.getUrl());
        return fileUrl.toString();
    }

    /**
     * 初始化 oss 客户端
     * @param ossConfig
     * @return
     */
    private static OSSClient initOSS(OSSConfig ossConfig) {
        if (ossClient == null ) {
            synchronized (OSSBootUtil.class) {
                if (ossClient == null) {
                    ossClient = new OSSClient(ossConfig.getEndpoint(),
                            new DefaultCredentialProvider(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret()),
                            new ClientConfiguration());
                }
            }
        }
        return ossClient;
    }

    /**
     * 根据前台传过来的文件地址 删除文件
     * @author jiangpengcheng
     * @param objectName
     * @param ossConfig
     * @return
     */
    public static ResponseResult delete(String objectName,OSSConfig ossConfig) {
        initOSS(ossConfig);
        //将完整路径替换成 文件地址 因为yml里的url有了地址链接https: //oos-all.oss-cn-shenzhen.aliyuncs.com/
        // 如果再加上地址 那么又拼接了 所以删除不了 要先把地址替换为 jpc/2020-07-16/1594857669731-51d057b0-9778-4aed.png
        String fileName = objectName.replace("https://oos-all.oss-cn-shenzhen.aliyuncs.com/", "");
        System.out.println(fileName+"******************************");
        // 根据BucketName,objectName删除文件
        ossClient.deleteObject(ossConfig.getBucketName(), fileName);

        return ResponseResult.ok("删除成功",fileName);
    }
}

Data return tools

package com.sykj.util;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @ClassName ResponseResult
 * @Description TODO
 * Author JiangPengCheng
 * Date 2020/7/15 9:13
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseResult implements Serializable {
    private Integer code;
    private String  message;
    private Object object;

    public static ResponseResult ok(String message){
        return new ResponseResult(200,message,null);
    }

    public static ResponseResult ok(String message, Object object){
        return new ResponseResult(200,message,object);
    }

    public static  ResponseResult error(String message){
        return new ResponseResult(500,message,null);
    }
    public static  ResponseResult error(String message, Object o){
        return new ResponseResult(500,message,o);
    }
}

Service class

package com.sykj.service;

import com.sykj.util.ResponseResult;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Description: 公共业务
 * @Author: junqiang.lu
 * @Date: 2018/12/24
 */
public interface CommonService {

    /**
     * 上传文件至阿里云 oss
     *
     * @param file
     * @param
     * @return
     * @throws Exception
     */
    ResponseResult uploadOSS(MultipartFile file) throws Exception;

     ResponseResult delete(String objectName);
}

Service implementation class

package com.sykj.service.impl;

import com.sykj.config.OSSConfig;
import com.sykj.service.CommonService;
import com.sykj.util.OSSBootUtil;
import com.sykj.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 公共业务具体实现类
 * @Author: junqiang.lu
 * @Date: 2018/12/24
 */
@Service("commonService")
public class CommonServiceImpl implements CommonService {

    @Autowired
    private OSSConfig ossConfig;

    /**
     * 上传文件至阿里云 oss
     *
     * @param file
     * @param
     * @return
     * @throws Exception
     */
    @Override

    public ResponseResult uploadOSS(MultipartFile file) throws Exception {

        // 格式化时间
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        // 高依赖版本 oss 上传工具
        String ossFileUrlBoot = null;
        /**
         * ossConfig 配置类
         * file 文件
         * "jpc/"+format 上传文件地址 加时间戳
         */
        ossFileUrlBoot = OSSBootUtil.upload(ossConfig, file, "jpc/"+format);
        System.out.println(ossFileUrlBoot);
        Map<String, Object> resultMap = new HashMap<>(16);
//        resultMap.put("ossFileUrlSingle", ossFileUrlSingle);
        resultMap.put("ossFileUrlBoot", ossFileUrlBoot);

       return ResponseResult.ok("上传成功~~",ossFileUrlBoot);
    }

    @Override
    public ResponseResult delete(String objectName) {
        ResponseResult delete = OSSBootUtil.delete(objectName, ossConfig);
        return delete;
    }
}

Controller class

package com.sykj.comtroller;
import com.sun.org.apache.regexp.internal.RE;
import com.sykj.service.CommonService;
import com.sykj.util.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Description: 公共模块控制中心
 * @Author: junqiang.lu
 * @Date: 2018/12/24
 */
@RestController
@RequestMapping("api/demo/common")
public class CommonController {

    private static final Logger logger = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private CommonService commonService;

    /**
     * 上传文件至阿里云 oss
     *
     * @param file
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/upload/oss", method = {RequestMethod.POST}, produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseResult uploadOSS(@RequestParam(value = "file") MultipartFile file) throws Exception {
        System.out.println(file.getInputStream());
//        ResponseResult responseResult = commonService.uploadOSS(file);

//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        return ResponseResult.ok("ok");
    }

   @RequestMapping("/delete/oss")
    public ResponseResult deltetOss(String objectName){
       System.out.println(objectName+"-------------------------------");
       ResponseResult delete = commonService.delete(objectName);
       return delete;
   }

}

Note that postman selects file

This is done

At last

Thank you for seeing here. After reading, if you have any questions, you can ask me in the comment area. If you think the article is helpful to you, remember to give me a thumbs up. You will share java-related technical articles or industry information every day. Welcome everyone's attention and Forward the article!

Guess you like

Origin blog.csdn.net/weixin_47277170/article/details/108122271