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
        }
    }
    
  • 相关阅读:
    spring IOC --- 控制反转(依赖注入)----简单的实例
    Spring MVC 返回视图时添加的模型数据------POJO
    Controller接口控制器3
    Controller接口控制器2
    Controller接口控制器
    Spring-MVC:应用上下文webApplicationContext
    DispatcherServlet 前置控制器
    WEB安全 asp+access注入
    WEB安全 Sqlmap 中绕过空格拦截的12个脚本
    Python 爬虫练习(三) 利用百度进行子域名收集
  • 原文地址:https://www.cnblogs.com/liangyy/p/13331747.html
Copyright © 2011-2022 走看看