Grails3檔案上傳到騰訊COS(OSS)

Genee發表於2018-11-29

build.gradle中引入依賴

// 騰訊雲oss
compile ('com.qcloud:cos_api:5.4.9') {
	exclude group: 'org.slf4j', module: 'slf4j-log4j12'
}
複製程式碼

grails-app/conf下建立一個application-oss.yml檔案

oss:
  secretId: AKI**************************H7Ti
  secretKey: FN**************************Ns
  regionName: ap-chengdu
  bucket: img-555231231
  accessAddr: http://www.baidu.com # 訪問地址
複製程式碼

然後在application.yml中加入

spring:
    profiles:
        include: oss
複製程式碼

新建一個TencentConfigJavaBean

  • 可以直接在grails-app/utils下,也可以在src/main/java
package first.blood.cn.tools.oss.tencent;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * 騰訊雲oss初始化配置
 * @Author Lee
 * @Description
 * @Date 2018年11月18日 18:51
 */
@Configuration
@ConfigurationProperties(prefix = "oss")
public class TencentConfig {

    private String secretId;

    private String secretKey;

    private String regionName;

    private String bucket;

    //訪問時的域名
    private String accessAddr;

    public String getAccessAddr() {
        return accessAddr;
    }

    public void setAccessAddr(String accessAddr) {
        this.accessAddr = accessAddr;
    }

    public String getSecretId() {
        return secretId;
    }

    public void setSecretId(String secretId) {
        this.secretId = secretId;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getRegionName() {
        return regionName;
    }

    public void setRegionName(String regionName) {
        this.regionName = regionName;
    }

    public String getBucket() {
        return bucket;
    }

    public void setBucket(String bucket) {
        this.bucket = bucket;
    }
}
複製程式碼

接下來建立一個檔案上傳的配置類(工具類)TencentOss

  • 與前面的TencentConfig放在一個包下
package first.blood.cn.tools.oss.tencent;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author Lee
 * @Description
 * @Date 2018年11月18日 18:35
 */
@Component
public class TencentOss {

    @Autowired
    private TencentConfig tc;

    /**
     * 上傳至騰訊雲COS
     *
     * @param inputStream 輸入流
     * @param fileName    儲存路徑+檔名:/2018/11/21/demo.png
     * @param contentType 檔案型別,預設是 application/octet-stream
     * @return
     */
    public String upload(InputStream inputStream, String fileName) throws IOException {

        COSClient cosClient = null;

        try {

            // 1 初始化使用者身份資訊(secretId, secretKey)
            COSCredentials cred = new BasicCOSCredentials(tc.getSecretId(), tc.getSecretKey());
            // 2 設定bucket的區域, COS地域的簡稱請參照 https://cloud.tencent.com/document/product/436/6224
            // clientConfig中包含了設定region, https(預設http), 超時, 代理等set方法, 使用可參見原始碼或者介面文件FAQ中說明
            ClientConfig clientConfig = new ClientConfig(new Region(tc.getRegionName()));
            // 配置使用https
            // 3 生成cos客戶端
            cosClient = new COSClient(cred, clientConfig);
            // bucket的命名規則為{name}-{appid} ,此處填寫的儲存桶名稱必須為此格式
            String bucketName = tc.getBucket();

            ObjectMetadata objectMetadata = new ObjectMetadata();

            PutObjectResult putObjectResult = cosClient.putObject(bucketName, fileName, inputStream, objectMetadata);

            String etag = putObjectResult.getETag();

        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (cosClient != null) {
                cosClient.shutdown();
            }
        }
        return tc.getAccessAddr() + "/" + fileName;
    }
}
複製程式碼

然後在程式入口類上加上@ComponetScan註解

package first.blood

import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import org.springframework.context.annotation.ComponentScan

@ComponentScan
class Application extends GrailsAutoConfiguration {
    static void main(String[] args) {
        GrailsApp.run(Application, args)
    }
}
複製程式碼

控制器方法

/**
 *  單檔案上傳
 * @return
 */
def imgFile() {

    def map = [success: 0, message: "上傳失敗"]
    def file = null
    def inputStream = null
    try {

        file = params["editormd-image-file"]
        inputStream = file.getInputStream()

        String fileName = file.getOriginalFilename()

        if (!file && !fileName) {
            map.message = "請選擇圖片檔案"
            render map as JSON
            return
        }

        // 判斷檔案大小,MAX_POST_SIZE自己定義
        if (file.getSize() > MAX_POST_SIZE) {
            map.message = "只能上傳不超過2M的圖片檔案"
            render map as JSON
            return
        }

        // 判斷是否是圖片檔案
        if (!ImgUtils.isImage(file.getInputStream())) {
            map.message = "只允許上傳圖片檔案"
            render map as JSON
            return
        }

        String prefix = fileName.substring(fileName.lastIndexOf("."))
        // 新檔名,這裡呼叫Date工具類生成目錄結構2018/12/30
        String newFileName = DateUtils.getUrl() + "/" + UUIDUtils.id() + prefix

        String accessAddr = oss.upload(inputStream,newFileName)
        map.success = 1
        map.message = "上傳成功"
        map.url = accessAddr
    } catch (e) {
        log.error("檔案上傳失敗,msg={}", e)
        map.message = "請檢查引數是否正確,只能上傳不超過2M的圖片檔案"
    }
    render map as JSON
}
複製程式碼

踩坑注意事項

  • 檔案流只能用一次
    • 前面定義了inputStream在中途用過一次就會出問題,上傳的檔案只有幾B大小,有的是0B

相關文章