English | 简体中文
基于 Nest(node.js) 框架封装的 阿里云对象存储 OSS 模块。
- 创建阿里云账号
- 购买对象存储服务. (产品链接)
- 创建 Bucket, 到 控制台 > 对象存储服务 > Bucket 列表 > 创建 Bucket
$ npm install --save nestjs-alicloud-oss
#or
$ yarn add nestjs-alicloud-oss
- 使用如下配置导入
AlicloudOssModule
:
import { Module } from '@nestjs/common';
import { AlicloudOssModule } from 'nestjs-alicloud-oss';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
controllers: [AppController],
providers: [AppService],
imports: [
AlicloudOssModule.withConfig({
options: {
accessKeyId: '******',
accessKeySecret: '******',
region: '******', // bucket的地区, 下面的例子使用 'oss-cn-beijing'.
bucket: '******', // 默认的 bucket, 面的例子使用 'nest-alicloud-oss-demo'.
},
}),
],
})
export class AppModule {}
你可以设置一个默认的
bucket
来应用于整个应用的所有控制器 controller, 你也可以在在控制器的路由中重写 它,以使用不同的bucket
。
import { Controller, Logger, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { AlicloudOssFileInterceptor, UploadedFileMetadata } from 'nestjs-alicloud-oss';
@Controller()
export class AppController {
@Post('upload')
@UseInterceptors(AlicloudOssFileInterceptor('file'))
UploadedFileUsingInterceptor(
@UploadedFile()
file: UploadedFileMetadata,
) {
console.log(file.objectUrl);
// http://nest-alicloud-oss-demo.oss-cn-beijing.aliyuncs.com/filename
}
}
import { Controller, Logger, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { AlicloudOssFileInterceptor, UploadedFileMetadata } from 'nestjs-alicloud-oss';
@Controller()
export class AppController {
@Post('upload2')
@UseInterceptors(
AlicloudOssFileInterceptor('file', null, {
{ folder: 'x/y/z', bucket: 'nest-alicloud-oss-demo2' },
}),
)
UploadedFilesUsingInterceptor(
@UploadedFile()
file: UploadedFileMetadata,
) {
console.log(file.objectUrl);
// http://nest-alicloud-oss-demo2.oss-cn-beijing.aliyuncs.com/x/y/z/filename
}
}
import { Controller, Logger, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { AlicloudOssService, UploadedFileMetadata } from 'nestjs-alicloud-oss';
@Controller()
export class AppController {
constructor(private readonly ossService: AlicloudOssService) {}
@Post('upload3')
@UseInterceptors(FileInterceptor('file'))
async UploadedFilesUsingService(
@UploadedFile()
file: UploadedFileMetadata,
) {
file = {
...file,
customName: 'customFilename.txt',
folder: 'a/b/c',
bucket: 'nest-alicloud-oss-demo3'
};
const url = await this.ossService.upload(file);
console.log(url)
// http://nest-alicloud-oss-demo3.oss-cn-beijing.aliyuncs.com/a/b/c/customFilename.txt
console.log(file.objectUrl);
// http://nest-alicloud-oss-demo3.oss-cn-beijing.aliyuncs.com/a/b/c/customFilename.txt
}
}
The MIT License.