SpringBoot中整合阿里雲OSS存儲

2022年12月19日14:03:04 科技 1227

我們在進行項目開發時,經常需要進行文件、圖片等的上傳。對於很多項目來說,雖然有FastDFS等文件存儲服務器技術,但其實我們完全沒有必要搭建自己的圖片等文件服務器。對一個小型非專業的應用來說,搭建自己的專屬文件存儲服務器,完全就是浪費,而且你們公司也不一定有那樣的技術實力。

但我們項目中又經常需要進行圖片等各種文件的上傳、下載操作,那該如何實現呢?

這裡壹哥給大家推薦使用阿里雲存儲,便宜又靠譜!所以今天 壹哥 會帶大家學習如何使用阿里雲的OSS實現文件上傳。

一. 阿里雲OSS簡介

1. 存儲服務簡介

阿里雲提供了一個對象存儲 OSS服務,可以實現海量、安全、低成本、高可靠的雲存儲服務,提供99.9999999999%的數據可靠性。並且使用RESTful API 可以在互聯網任何位置存儲和訪問,容量和處理能力彈性擴展,多種存儲類型供選擇全面優化存儲成本。

2. 購買阿里雲OSS服務

首選搜索阿里雲,選擇第一個就是了。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

然後選擇雲計算基礎里的對象存儲OSS產品。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

可以看到,40G的一年存儲服務才9塊錢,很便宜了,對於學習來說足夠了。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

3. 阿里雲OSS控制台

點擊首頁的控制台鏈接就可以進入後台。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

在這裡創建一個Bucket桶,作為存儲文件的空間。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

桶名不能重複。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

可以在自己的桶空間中創建子目錄,用來存儲不同項目或模塊下的文件。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

接下來要設置該目錄的訪問權限,可以設置為公共讀。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

再設置一下該桶的授權策略。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

二. SpringBoot中實現OSS雲存儲

1. 創建Web項目

我們按照之前的經驗,創建一個web程序,並將之改造成Spring Boot項目,具體過程略。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

2. 添加依賴包

	  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <!--簡化bean代碼-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        
         <!-- Thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- 圖片上傳 SDK 阿里雲oss -->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.8.3</version>
        </dependency>
        <dependency>
            <groupId>commons-Fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
</dependency>

3.創建配置信息

可以在這裡查看自己阿里雲賬號的AccessKey信息。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

bucketName: "yiyige"
accessKeyId: "自己阿里雲的accessKey"
accessKeySecret: "自己阿里雲的accessKey"
#OSS對應的區域
endpoint: "http://oss-cn-hangzhou.aliyuncs.com"
filehost: "images"

4. 創建配置信息類

package com.yyg.boot.config;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * 把配置文件中的配置信息讀取到該類中.
 */
@Data
@Configuration
public class OssConfiguration {

    @Value("${endpoint}")
    private String endPoint;

    @Value("${accessKeyId}")
    private String accessKeyId;

    @Value("${accessKeySecret}")
    private String accessKeySecret;

    @Value("${filehost}")
    private String fileHost;

    @Value("${bucketName}")
    private String bucketName;

}

5. 封裝阿里雲文件上傳工具類

package com.yyg.boot.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.yyg.boot.config.OssConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 封裝文件上傳方法
 */
@Component
public class AliyunOssUtil {

    @Autowired
    private OssConfiguration config;

    public String upload(File file) {
        if (file == null) {
            return null;
        }

        String endPoint = config.getEndPoint();
        String keyId = config.getAccessKeyId();
        String keySecret = config.getAccessKeySecret();
        String bucketName = config.getBucketName();
        String fileHost = config.getFileHost();
        
        //定義子文件的格式
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        //阿里雲文件上傳客戶端
        OSSClient client = new OSSClient(endPoint, keyId, keySecret);

        try {
            //判斷桶是否存在
            if (!client.doesBucketExist(bucketName)) {
                //創建桶
                client.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                //設置訪問權限為公共讀
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                //發起創建桶的請求
                client.createBucket(createBucketRequest);
            }

            //當桶存在時,進行文件上傳
            //設置文件路徑和名稱
            String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
            PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);

            //文件上傳成功後,返回當前文件的路徑
            if (result != null) {
                return fileUrl;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }

        return null;
    }

}

6. 編寫Controller接口

package com.yyg.boot.web;

import com.yyg.boot.util.AliyunOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;

@Controller
public class OssController {

    @Autowired
    private AliyunOssUtil ossUtil;

    @GetMapping("/")
    public String showUploadFile() {
        return "upLoad";
    }

    @PostMapping("/uploadFile")
    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file != null) {
                String fileName = file.getOriginalFilename();
                if (!"".equals(fileName.trim())) {
                    File newFile = new File(fileName);
                    
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();

                    //把file里的內容複製到奧newFile中
                    file.transferTo(newFile);
                    String upload = ossUtil.upload(newFile);

                    //圖片回顯地址:
                    //http://yiyige.oss-cn-hangzhou.aliyuncs.com/images/2019-10-21/6c964702b67d4eeb920e7f1f4358189b-dishu.jpg
                    System.out.println("path=" + upload);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "success";
    }

}

7. 編寫文件上傳頁面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta charset="UTF-8"/>
    <title>【基於OSS的上傳文件頁面】</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"  media="all"/>
    <style type="text/css">
        *{
            margin:0;
            padding:0;
        }
        #group{
            position: absolute;
            left:580px;
        }
        #submit{
            position: absolute;
            top:140px;
            left:580px;
        }
    </style>
</head>
<body>
<div align="center">
    <h2 style="color:orangered;">基於OSS的上傳文件頁面</h2>
</div>
<br/>
<form action="/uploadFile" enctype="multipart/form-data" method="post">
    <div class="form-group" id="group">
        <label for="exampleInputFile">File input</label>
        <input type="file" id="exampleInputFile" name="file"/>
    </div>
    <button type="submit" class="btn btn-default" id="submit">上傳</button>
</form>
</body>
</html>

8. 文件上傳成功界面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta charset="UTF-8"/>
    <title>【文件上傳成功頁面】</title>
</head>
<body>
<div align="center">
    <h5>上傳成功</h5>
</div>
</body>
</html>

9. 編寫入口類

package com.yyg.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class OssApplication {

    public static void main(String[] args) {
        SpringApplication.run(OssApplication.class, args);
    }

}

10. 進行測試

首先進入到文件上傳界面,選擇一個文件進行上傳。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

上傳成功。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

打開控制台,可以看到阿里雲OSS服務器端返回的圖片路徑。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

然後我們去阿里雲服務器上可以看到自動以當天日期創建了一個文件夾,這裡存放的就是當天上傳的文件。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

在這個文件夾里看到剛才上傳的圖片文件。

SpringBoot中整合阿里雲OSS存儲 - 天天要聞

結語

至此,壹哥 就把阿里雲OSS的使用教程給大家介紹完了,現在你學會了嗎?最後壹哥可以偷偷告訴你一個小秘訣,你完全可以利用阿里雲OSS搭建一個自己的私密「雲盤」哦,至於裏面存什麼內容,自己悟吧!

作者:一一哥Sun
鏈接:https://juejin.cn/post/7178627128269733949
來源:稀土掘金

科技分類資訊推薦

引領科技豪華MPV新風尚 第二代騰勢D9西安車展亮相 - 天天要聞

引領科技豪華MPV新風尚 第二代騰勢D9西安車展亮相

兼具宜商氣度與家用溫情的科技豪華旗艦MPV,第二代騰勢D9迎來西安地區正式亮相。新車依託全球新能源MPV冠軍底蘊,以第二代刀片電池、雙閥雲輦-C、天神之眼5.0智駕等核心技術全面升級,兼顧商務體面與家庭舒適,為西北高端用戶帶來一站式全能出行解決方案。
採購禁入!科華數據材料造假被拒門外 - 天天要聞

採購禁入!科華數據材料造假被拒門外

本報(chinatimes.net.cn)記者胡雅文 北京報道這家趕上AI算力風口的公司,因投標材料造假,被相關採購方列入禁入名單兩年,其此前提出的複議申請也被正式駁回。相關採購平台近日發佈公告,明確駁回科華數據股份有限公司(下稱「科華數據」,002335.SZ)此前提交的複議申請。早在一年前,科華數據已被認定在「信息通信樞紐...
快評樂道L80:15萬元級買大五座,這波值得沖? - 天天要聞

快評樂道L80:15萬元級買大五座,這波值得沖?

日前,樂道L80正式發佈並開啟預售,其整車購買預售價為24.58萬元起,租電購買預售價則低至15.98萬元起。面對大型SUV市場「細分再細分」之競爭趨勢,這款樂道年度重磅新車都有哪些優勢?又能否成為「大五座SUV革新之作」?下面,圈哥就帶大家全方位感受。
成都直擊凱威德:純電全尺寸SUV的張揚與大氣 - 天天要聞

成都直擊凱威德:純電全尺寸SUV的張揚與大氣

4月22日,凱迪拉克以奧斯卡級盛典規格,將上海保利大劇院點亮為璀璨舞台,在品牌代言人倪妮與全場嘉賓的共同見證下,凱迪拉克全尺寸純電公路旗艦——凱威德耀然上市。新車共推出長續航四驅Pro、高性能四驅Ultra兩款配置,官方售價區間為46.88萬-50.88萬元。