nestjs使用oss做文件上传
官网:https://help.aliyun.com/document_detail/32068.html?spm=a2c4g.11174283.6.1259.7bc17da2koCrAk
- 安装:
npm install @types/ali-oss
- 使用
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
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现