zoukankan      html  css  js  c++  java
  • 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: "LTAI1233kixxxxx",
                accessKeySecret: "b166MvJ2p39yF123HTedlhAxxxxxx",
                bucket: "*****",
            })
        }
        /**
         * 上传文件
         * @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
        }
    }
    
  • 相关阅读:
    494 Target Sum 目标和
    493 Reverse Pairs 翻转对
    492 Construct the Rectangle 构建矩形
    491 Increasing Subsequences 递增子序列
    488 Zuma Game 祖玛游戏
    486 Predict the Winner 预测赢家
    485 Max Consecutive Ones 最大连续1的个数
    483 Smallest Good Base
    Django Form组件
    Django Auth组件
  • 原文地址:https://www.cnblogs.com/liangyy/p/13331747.html
Copyright © 2011-2022 走看看