SpringBoot整合阿里云OSS

阿里云OSS

為了解決海量數(shù)據(jù)存儲(chǔ)與彈性擴(kuò)容,我們一般采用云存儲(chǔ)的解決方案-阿里云OSS。

一、測(cè)試Bucket

Bucket可以理解為電腦上的磁盤(pán)

引入相關(guān)依賴(lài)

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.1.0</version>
</dependency>

測(cè)試創(chuàng)建Bucket的連接。其中:

  1. endpoint :創(chuàng)建Bucket后概覽頁(yè)面獲取
  2. accessKeyId :可由右上角個(gè)人信息中AccessKey管理獲取
  3. accessKeySecret :可由右上角個(gè)人信息中AccessKey管理獲取
  4. bucketName :創(chuàng)建Bucket時(shí)的名稱(chēng)
public class TestOSS {

    // yourEndpoint填寫(xiě)B(tài)ucket所在地域?qū)?yīng)的Endpoint。以華東1(杭州)為例,Endpoint填寫(xiě)為https://oss-cn-hangzhou.aliyuncs.com。
    String endpoint = "your-endpoint";
    // 阿里云賬號(hào)AccessKey擁有所有API的訪(fǎng)問(wèn)權(quán)限,風(fēng)險(xiǎn)很高。強(qiáng)烈建議您創(chuàng)建并使用RAM用戶(hù)進(jìn)行API訪(fǎng)問(wèn)或日常運(yùn)維,請(qǐng)登錄RAM控制臺(tái)創(chuàng)建RAM用戶(hù)。
    String accessKeyId = "your-accessKeyId ";
    String accessKeySecret = "your-accessKeySecret ";
    // 填寫(xiě)B(tài)ucket名稱(chēng),例如examplebucket。
    String bucketName = "your-bucketName  ";

    @Test
    public void testCreateBucket() {
        // 創(chuàng)建OSSClient實(shí)例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 創(chuàng)建存儲(chǔ)空間
        ossClient.createBucket(bucketName);
        // 關(guān)閉ossClient
        ossClient.shutdown();
    }

}

判斷存儲(chǔ)空間是否存在

@Test
public void testExist() {
    // 創(chuàng)建OSSClient實(shí)例
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

    boolean exist = ossClient.doesBucketExist(bucketName);
    System.out.println(exist);

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

}

二、文件上傳

配置application.properties

#服務(wù)端口
server.port=8080

# 應(yīng)用名稱(chēng)
spring.application.name=OssDemo01

#阿里云 OSS
#不同的服務(wù)器,地址不同
aliyun.oss.file.endpoint=your Endpoint
aliyun.oss.file.keyid=your AccessKeyID
aliyun.oss.file.keysecret=your AccessKeySecret
#bucket可以在控制臺(tái)創(chuàng)建,也可以使用java代碼創(chuàng)建
aliyun.oss.file.bucketname=your BucketName

從配置文件讀取常量
創(chuàng)建常量讀取工具類(lèi):ConstantPropertiesUtil.java
使用@Value讀取 application.properties 里的配置內(nèi)容
用 Spring 的 InitializingBean 的 afterPropertiesSet 來(lái)初始化配置信息,這個(gè)方法將在所有的屬性被初始化后調(diào)用。

/**
 * 常量類(lèi),讀取配置文件application.properties中的配置
 */
@Component
//@PropertySource("classpath:application.properties")
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.filehost}")
    private String fileHost;

    @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;
    public static String FILE_HOST ;

    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT = endpoint;
        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
        BUCKET_NAME = bucketName;
        FILE_HOST = fileHost;
    }
}

創(chuàng)建service接口

public interface IFileService {

    /**
     * 文件上傳至阿里云
     * @param file
     * @return
     */
    String upload(MultipartFile file);
}

實(shí)現(xiàn)接口

@Service
public class FileService Impl implements IFileService {

    @Override
    public String upload(MultipartFile file) {
        //工具類(lèi)獲取值
        String endpoint = ConstantPropertiesUtil.END_POIND;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        try {
            // 創(chuàng)建OSSClient實(shí)例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

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

            //獲取文件名稱(chēng)
            String fileName = file.getOriginalFilename();

            //存在問(wèn)題:多次上傳相同文件的名稱(chēng),造成最后一次上傳把之前上傳文件覆蓋
            //解決:方式1.在文件名稱(chēng)里面添加隨機(jī)唯一的值
            String uuid = UUID.randomUUID().toString().replace("-", "");
            fileName = uuid + fileName;
            //方式2  把文件按照日期進(jìn)行分類(lèi)
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath +"/" + fileName;

            //調(diào)用oss方法實(shí)現(xiàn)上傳
            //第一個(gè)參數(shù):Bucket名稱(chēng)
            //第二個(gè)參數(shù):上傳到oss文件路徑和文件名稱(chēng)
            //第三個(gè)參數(shù):上傳文件輸入流
            ossClient.putObject(bucketName,fileName,inputStream);

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

            //把上傳之后的文件路徑返回
            String url = "https://" + bucketName + "."+endpoint + "/" + fileName;
            return url;
        }catch (Exception e){

            e.printStackTrace();
            return null;

        }
    }
}

控制層

@RestController
@RequestMapping("/file/upload")
@AllArgsConstructor
public class FileController {

    private final IFileService fileService;

    @PostMapping
    public String upload(MultipartFile file){
        //獲取上傳文件 MultipartFile
        //返回上傳到oss的路徑
        String url = fileService.upload(file);
        return url;
    }

}
最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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