SpringBoot整合阿里oss對(duì)象存儲(chǔ)

創(chuàng)建阿里云賬戶并開通oss服務(wù)
創(chuàng)建Bucket,生成Access Key

官方api文檔

https://help.aliyun.com/document_detail/32008.html?spm=5176.208357.1107607.21.7fa1390fHFxgTB

代碼整合oss
  1. pom文件引入sdk依賴
<!-- jdk1.8依賴 -->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.10.2</version>
</dependency>

<!--如果使用的是Java 9及以上的版本,則需要添加jaxb相關(guān)依賴。添加jaxb相關(guān)依賴示例代碼如下: -->
<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>

  1. properties配置文件
#服務(wù)端口
server.port=8002
#服務(wù)名
spring.application.name=service-oss
#環(huán)境設(shè)置:dev、test、prod
spring.profiles.active=dev
#阿里云 OSS
#不同的服務(wù)器,地址不同
#創(chuàng)建Bucket時(shí)選的地域節(jié)點(diǎn)信息,可在Bucket列表詳情概述中查看
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
#創(chuàng)建Access Key的key值
aliyun.oss.file.keyid=LTAI5tRuAjqAmc
#創(chuàng)建Access Key的keysecret值
aliyun.oss.file.keysecret=gpNzRGENhHmr5ut
#bucket可以在控制臺(tái)創(chuàng)建,也可以使用java代碼創(chuàng)建
#bucket名稱
aliyun.oss.file.bucketname=demo-01
  1. 創(chuàng)建config類讀取配置信息
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 常量類,讀取配置文件application.properties中的配置
 */
@Component
public class ConstantPropertiesUtil implements InitializingBean {

    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.keyid}")
    private String keyId;

    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;

    @Value("${aliyun.oss.file.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;

    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT = endpoint;
        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
        BUCKET_NAME = bucketName;
    }
}
  1. 創(chuàng)建controller類,上傳文件接口
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Api(description="阿里云文件管理")
@CrossOrigin //跨域
@RestController
@RequestMapping("/oss/file")
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 文件上傳
     *
     * @param file
     */
    @ApiOperation(value = "文件上傳")
    @PostMapping("upload")
    public R upload(
            @ApiParam(name = "file", value = "文件", required = true)
            @RequestParam("file") MultipartFile file) {

        String uploadUrl = fileService.upload(file);
        //返回r對(duì)象
        return R.ok().message("文件上傳成功").data("url", uploadUrl);

    }
}
  1. 創(chuàng)建service接口
import org.springframework.web.multipart.MultipartFile;

public interface FileService {

    /**
     * 文件上傳至阿里云
     * @param file
     * @return
     */
    String upload(MultipartFile file);
}
  1. 創(chuàng)建serviceImpl類實(shí)現(xiàn)接口方法
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file) {

        //獲取阿里云存儲(chǔ)相關(guān)常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        String uploadUrl = null;

        try {
            //判斷oss實(shí)例是否存在:如果不存在則創(chuàng)建,如果存在則獲取
            OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
            if (!ossClient.doesBucketExist(bucketName)) {
                //創(chuàng)建bucket
                ossClient.createBucket(bucketName);
                //設(shè)置oss實(shí)例的訪問權(quán)限:公共讀
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }

            //獲取上傳文件流
            InputStream inputStream = file.getInputStream();

            /*
            * 此處對(duì)文件進(jìn)行日期加uuid重命名,解決用戶上傳重復(fù)名文件覆蓋問題
            *構(gòu)建日期路徑:avatar/2019/02/26/文件名
            * new DateTime()引入了一個(gè)org.joda.time的jar
            * 此處報(bào)錯(cuò)的朋友可以使用 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") 制定日期輸出格式
            * */
            String filePath = new DateTime().toString("yyyy/MM/dd");

            //文件名:uuid.擴(kuò)展名
            String original = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString().replace("-","");
            String fileType = original.substring(original.lastIndexOf("."));
            String newName = fileName + fileType;
            String fileUrl = filePath + "/" + newName;

            //文件上傳至阿里云
            ossClient.putObject(bucketName, fileUrl, inputStream);

            // 關(guān)閉OSSClient。
            ossClient.shutdown();

            //獲取url地址
            uploadUrl = "https://" + bucketName + "." + endPoint + "/" + fileUrl;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return uploadUrl;
    }
}
  1. swagger進(jìn)行上傳測(cè)試




    至此oss上傳文件整合完畢

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容