天天看點

使用阿裡雲的OSS儲存圖檔

  簡單說一下這個OSS幹啥用的,我們知道mysql這種關系型資料庫最好不要存長文本還有二進制資料,比如圖檔,檔案等,那麼這些檔案和圖檔放哪裡呢?

  本篇說的就是放到阿裡雲的OSS中去,然後資料庫中隻存放對應的url,我們隻需要拿着這個url就可以通路到我們需要的資源;例如使用者頭像,還有需要商品的圖檔等等;

1.首先到阿裡雲中進入到OSS中,然後去建立一個Bucket,下面這樣:

使用阿裡雲的OSS儲存圖檔
使用阿裡雲的OSS儲存圖檔

   

  隻用修改下面三個,其他的都是預設就行,注意這個bucket的名字很重要,後面在java代碼中需要配置:

使用阿裡雲的OSS儲存圖檔

2.然後進入到建立的bucket中,找到這個endpoint複制下來,後面會用到;

使用阿裡雲的OSS儲存圖檔

3.找到你阿裡雲自己的id和密鑰複制下來,後面會用到:

使用阿裡雲的OSS儲存圖檔

 4.建立一個springboot項目,并且常用的依賴(包括使用lombok和swagger)和OSS依賴,并且在properties配置檔案中配置前面前3步複制下來的東西:

<!-- 阿裡雲oss依賴 -->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
        </dependency>
        <!-- 日期工具欄依賴 -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>      
aliyun.oss.file.bucketname=你的bucket的名字
aliyun.oss.file.endpoint=你的endpoint路徑
aliyun.oss.file.keyid=你的阿裡雲的id
aliyun.oss.file.keysecret=你的阿裡雲的密鑰      

 5.使用一個類和上面properties檔案中的屬性綁定起來,友善我們使用:

package com.protagonist.utils;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "aliyun.oss.file")
public class ConstantPropertiesUtils{

    private String endpoint;

    private String keyid;

    private String keysecret;

    private String bucketname;

}      

 6.controller代碼,傳回儲存在OSS中檔案的全路徑,這個Result 就是一個對前端統一的類型,也可以直接傳回HashMap

package com.protagonist.controller;


import com.protagonist.responseVO.Result;
import com.protagonist.responseVO.StatusCode;
import com.protagonist.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;

@Api("檔案上傳")
@RestController
@RequestMapping("/eduoss")
@CrossOrigin
public class OssController {
    @Resource
    private OssService ossService;

    //上傳頭像的方法
    @PostMapping("/fileOss")
    @ApiOperation(value = "檔案上傳")
    public Result UploadOssFile(MultipartFile file) {
        String url = ossService.uploadFileAvatar(file);
        HashMap<String, String> map = new HashMap<>();
        map.put("url",url);
        return new Result<>(true, StatusCode.OK,"上傳成功",map);
    }
}      

 7.service代碼,隻需要修改那個自定義異常還有狀态碼,其他的不需要改:

package com.protagonist.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.protagonist.responseVO.StatusCode;
import com.protagonist.servicebase.exception.ProtagonistException;
import com.protagonist.utils.ConstantPropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

@Service
@Slf4j
public class OssService{

    @Resource
    private ConstantPropertiesUtils constantPropertiesUtils;

    public String uploadFileAvatar(MultipartFile file) {
        //擷取oss上傳配置檔案中的參數
        String bucketName = constantPropertiesUtils.getBucketname();
        String endpoint = constantPropertiesUtils.getEndpoint();
        String keyId = constantPropertiesUtils.getKeyid();
        String keySecret = constantPropertiesUtils.getKeysecret();

        OSS ossClient;
        InputStream inputStream;
        try {
            // 建立OSSClient執行個體。
            ossClient  = new OSSClientBuilder().build(endpoint, keyId, keySecret);
            // 上傳檔案流
            inputStream = file.getInputStream();

            //為了使得檔案可以重複上傳,每次上傳的時候需要将檔案名進行修改
            String fileName = file.getOriginalFilename();
            log.info("圖檔上傳的名字為:{}",fileName);
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String newFileName = uuid + fileName;

            //擷取目前日期,然後以日期和新的檔案名組成全路徑,使得oss中的檔案按照日期進行分類存儲
            String date = new DateTime().toString("yyyy/MM/dd");
            String fullFileName = date + "/" + newFileName;
            log.info("圖檔儲存在oss的全路徑為:{}",fullFileName);

            //第一個參數Bucket名稱 第二個參數 上傳到oss檔案路徑和檔案名稱
            ossClient.putObject(bucketName, fullFileName, inputStream);

            // 關閉OSSClient。
            ossClient.shutdown();
            return "https://"+bucketName+"."+ endpoint+"/"+fullFileName;
        } catch (Exception e) {
            log.error("檔案上傳失敗",e);
            throw new ProtagonistException(StatusCode.REMOTEERROR,"檔案上傳oss失敗");
        }
    }
}      

 8.測試,圖檔上傳成功,傳回OSS中儲存的url,然後前端就可以直接拿到這個url做些花裡胡哨的事!

使用阿裡雲的OSS儲存圖檔
使用阿裡雲的OSS儲存圖檔

  我們可以看看OSS中儲存的圖檔;

使用阿裡雲的OSS儲存圖檔

  其實這種圖檔還有檔案啥的,也可以自己自己搭建一個檔案伺服器丢到裡面去,簡單一點的使用docker,有興趣的可以試試!

使用阿裡雲的OSS儲存圖檔