NestJS 实现 OSS上传文件

2023-03-08 下午后端 194 次浏览暂无评论

前言

在使用 NestJS 的过程中,涉及到了 OSS 上传文件的功能,这里简单记录一下。

代码实现

oss.controller.ts

import { Controller, Post, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Result } from 'src/utils/ResultType';
import { OssService } from './oss.service';

@Controller({ path: 'oss', version: '1' })
export class OssController {
  constructor(private readonly ossService: OssService) { }

  @Post('uploadImage')
  @UseInterceptors(FileInterceptor('file'))
  async uploadImage(@UploadedFile() file: Express.Multer.File) {
    const res = await this.ossService.uploadFile('images/' + file.originalname, file.buffer, file.size)
    return Result.success(res)
  }
}

oss.service.ts

import { Injectable } from '@nestjs/common';
import * as OSS from 'ali-oss';

@Injectable()
export class OssService {
  private client: any
  constructor() {
    this.client = new OSS({
      region: 'oss-cn-hangzhou',
      accessKeyId: 'LTAI5tPH6aKN7Jo6Ft2CPkoU',
      accessKeySecret: 'SCG5GiJ1SAcvIJ7UMSRMtu4IUemQjy',
      bucket: 'somelight'
    })
  }
  public async uploadFile(ossPath: string, localPath: any, size: number): Promise<string> {
    if (size > 5 * 1024 * 1024) {
      return await this.resumeUpload(ossPath, localPath)
    } else {
      return await this.upload(ossPath, localPath)
    }
  }
  // oss put上传文件
  private async upload(ossPath: string, localPath: string): Promise<string> {

    const res = await this.client.put(ossPath, localPath)
    // 将文件设置为公共可读
    await this.client.putACL(ossPath, 'public-read')
    return res.url
  }

  // oss 断点上传
  private async resumeUpload(ossPath: string, localPath: string): Promise<string> {
    let checkPoint: number = 0
    let bRet = ''
    for (let i = 0; i < 3; i++) {
      let result = this.client.multipartUpload(ossPath, localPath, {
        checkPoint,
        async progress(percent: number, cpt: any) {
          checkPoint = cpt
        }
      })
      await this.client.putACL(ossPath, 'public-read')
      bRet = result.url
      break
    }
    return bRet
  }

  // 删除文件
  private async deleteOne(filePath: string) {
    if (!filePath) {
      return
    }
    await this.client.delete(filePath)
  }

  // 删除多个文件
  private async deleteMulti(filePathArr: string[]) {
    await this.client.deleteMulti(filePathArr, { quiet: true })
  }

  // 获取文件的url
  public async getFileSignatureUrl(filePath: string): Promise<string> {
    if (!filePath) {
      return null
    }
    const result = await this.client.signatureUrl(filePath, { expires: 36000 })
    return result
  }

  // 判断文件是否存在
  public async existObject(ossPath: string): Promise<boolean> {
    try {
      const result = await this.client.get(ossPath)
      if (result.res.status === 200) {
        return true
      }
    } catch (err) {
      if (err.code === 'NoSuchKey') {
        return false
      }
    }
  }
}

总结

以上就是我对NestJS处理OSS上传文件的一些总结。


目录

代码实现
总结
ICP备案号:鲁ICP备2020040322号