1. 程式人生 > 實用技巧 >nestjs使用oss做檔案上傳

nestjs使用oss做檔案上傳

官網:https://help.aliyun.com/document_detail/32068.html?spm=a2c4g.11174283.6.1259.7bc17da2koCrAk

  1. 安裝: npm install @types/ali-oss
  2. 使用
import * as OSS from 'ali-oss';
import { Inject, Injectable } from '@nestjs/common';

@Injectable()
export class OssHelper {
    private client : any
    public constructor() {
        this.client = new OSS({
            region: "oss-cn-qingdao",
            accessKeyId: "LTAI1233kiCKUWBi",
            accessKeySecret: "b166MvJ2p39yF123HTedlhA1WmwF6d",
            bucket: "blasting",
        })
    }
    /**
     * 上傳檔案
     * @param localPath 
     * @param ossPath 
     * @param size 
     */
    public async uploadFile(localPath: string, ossPath: string, size: number): Promise<string> {
        if (size > 5 * 1024 * 1024) {     // 設定MB
            return await this.resumeUpload(ossPath, localPath)
        } else {
            return await this.upload(ossPath, localPath)
        }
    }
    // oss put上傳檔案
    private async upload(ossPath: string, localPath: string): Promise<string> {
        let res 
        try {
          res = await  this.client.put(ossPath, localPath)
          // 將檔案設定為公共可讀
          await this.client.putACL(ossPath, "public-read")
        } catch (error) {
        console.log(error)
        }
        return res.url
    }
    // oss 斷點上傳
    private async resumeUpload(ossPath: string, localPath: string) {
        let checkpoint: any = 0
        let bRet = ''
        for (let i = 0; i < 3; i++) {
            try {
                let result =  this.client.get().multipartUpload(ossPath, localPath, {
                    checkpoint,
                    async progress(percent: number, cpt: any) {
                        checkpoint = cpt
                    }
                })
                // 將檔案設定為公共可讀
                await this.client.putACL(ossPath, "public-read")
                bRet = result.url
                break
            } catch (error) {
                // console.log(error)
            }
        }
        console.log('resumeUpload:::::', bRet)
        return bRet
    }
    /**
     * 刪除一個檔案
     */
    public async deleteOne(filepath: string) {
        if(filepath==null){
            return;
        }
        try {
            let result = this.client.delete(filepath);
        } catch (e) {
            console.log(e);
        }
    }

    /**
     * 刪除多個檔案
     * @param filepathArr 
     */
    public async deleteMulti(filepathArr: string[]): Promise<void> {
        try {
            let result = this.client.deleteMulti(filepathArr, { quiet: true });
            // console.log(result);
        } catch (e) {
            console.log(e);
        }
    }
    /**
     * 獲取檔案的url
     * @param filePath 
     */
    public async getFileSignatureUrl(filePath: string): Promise<string> {
        if (filePath == null) {
            console.log("get file signature failed: file name can not be empty");
            return null
        }
        let result = ""
        try {
            result = this.client.signatureUrl(filePath, { expires: 36000 })
        } catch (err) {
            console.log(err)
        }
        
        return result
    }
    // 判斷檔案是否存在
    public async existObject(ossPath: string): Promise<boolean> {
        try {
            let result = this.client.get(ossPath)
            if (result.res.status == 200) {
                return true
            }
        } catch (e) {
            if (e.code == 'NoSuchKey') {
                return false
            }
        }
        return false
    }
}