oss bucket创建
创建规则:
由于上传文件,设置为公共读
然后配置access_key
获取位置为:
新建后只能查看一次,然后在后端oss.service.ts配置对应config.service.ts即可
前端上传文件
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BE_URL } from '../constant';
@Injectable()
export class UploadService {
constructor(private httpClient: HttpClient) {}
// 上传文件
uploadFile(file: any) {
const formData = new FormData();
formData.append('file', file);
return this.httpClient.post<any>(`${BE_URL}/project/api/upload`, formData, {
params: {
_allow_anonymous: 'true'
}
});
}
}
调用服务
// 上传文件
this.uploadService.uploadFile(files[0]).subscribe(result => {
console.log({ result });
});
后端上传文件
import {
Controller,
Post,
Req,
UploadedFile,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { format } from 'date-fns';
import { nonceStr } from '../../shared/functions/utils';
import { MLogger } from '../../shared/modules/logger/logger.service';
import { OssService } from '../../shared/services/oss.service';
// 用于提供各种api的controller
@Controller('project/api')
export class ApiController {
private logger = new MLogger(this.constructor.name);
constructor(public ossService: OssService) {}
@Post('/upload')
@UseInterceptors(FileInterceptor('file'))
async uploadFile(@UploadedFile() file, @Req() req) {
const result = await this.ossService.uploadFile(
file.buffer,
`upload-files/${format(new Date(), 'yyyyMMdd')}/${nonceStr(5)}-${
file.originalname
}`,
);
return { ...result, filename: file.originalname };
}
}