@nestjs/common#UploadedFile TypeScript Examples
The following examples show how to use
@nestjs/common#UploadedFile.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: files.controller.ts From NestJs-youtube with MIT License | 6 votes |
@Post('upload')
@UseInterceptors(
FileInterceptor('file', {
storage: diskStorage({
destination: (req: Express.Request, file: Express.Multer.File, cb) =>
cb(null, 'public/uploads'),
filename: (req: Express.Request, file: Express.Multer.File, cb) => {
// mimetype: 'image/jpeg',
const [, ext] = file.mimetype.split('/');
FilesController.genericSercive.pcoket.filename = `${v4()}.${ext}`;
cb(null, FilesController.genericSercive.pcoket.filename);
},
}),
limits: {
fileSize: 1e7, // the max file size in bytes, here it's 100MB,
files: 1,
},
}),
)
uploadFile(@UploadedFile() file: Express.Multer.File): Promise<FileEntity> {
const [, ext] = file.mimetype.split('/');
this.saveImages(ext, file);
return this.service.dbSave(
file,
FilesController.genericSercive.pcoket.filename,
);
}
Example #2
Source File: app.controller.ts From nest-js-quiz-manager with MIT License | 6 votes |
@Post('/file')
@UseInterceptors(
FileInterceptor('file', {
storage: diskStorage({
destination: './uploads',
filename: (req, file, callback) => {
const uniqueSuffix =
Date.now() + '-' + Math.round(Math.random() * 1e9);
const ext = extname(file.originalname);
const filename = `${uniqueSuffix}${ext}`;
callback(null, filename);
},
}),
}),
)
handleUpload(@UploadedFile() file: Express.Multer.File) {
console.log('file', file);
return 'File upload API';
}
Example #3
Source File: surveys.controller.ts From aqualink-app with MIT License | 6 votes |
@ApiBearerAuth()
@ApiFileUpload()
@ApiCreatedResponse({
description: 'Returns the public url to access the uploaded media',
schema: {
type: 'string',
example:
'https://storage.googleapis.com/storage/reef-image-1029381082910831.jpg',
},
})
@ApiOperation({ summary: 'Uploads a new survey media' })
@ApiParam({ name: 'siteId', example: 1 })
@Post('upload')
@AcceptFile('file', ['image', 'video'], 'surveys', 'site')
upload(
@Param('siteId', ParseIntPipe) siteId: number,
@UploadedFile('file') file: any,
): string {
// Override file path because file.path provided an invalid google cloud format and HTTPS is not working correctly
// Correct format of a URL pointing to a google cloud object should be
// https://storage.googleapis.com/{bucketName}/path/to/object/in/bucket
return `https://storage.googleapis.com/${process.env.GCS_BUCKET}/${file.filename}`;
}
Example #4
Source File: profile.controller.ts From codeclannigeria-backend with MIT License | 6 votes |
@Post('upload_profile_photo')
@UseInterceptors(FileInterceptor('file'))
@ApiConsumes('multipart/form-data')
@ApiBody({
description: 'Upload avatar photo',
type: AvatarUploadDto
})
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiResponse({ type: UserDto, status: HttpStatus.OK })
@HttpCode(HttpStatus.OK)
async uploadFile(
@UploadedFile() file: BufferedFile,
@Req() req: Request
): Promise<UserDto> {
if (!file) throw new BadRequestException('File image cannot be empty');
if (file.mimetype.split('/')[0] !== 'image')
throw new UnsupportedMediaTypeException('File is not an image');
if (file.size / 1024 > 200)
throw new BadRequestException('File cannot be larger than 200KB');
const id = req.user['userId'];
await this.profileService.uploadAvatar(file, id);
const user = await this.userService.findByIdAsync(id);
return plainToClass(UserDto, user, {
enableImplicitConversion: true,
excludeExtraneousValues: true
});
}
Example #5
Source File: tracks.controller.ts From codeclannigeria-backend with MIT License | 6 votes |
@Post('create_with_thumbnail')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN, UserRole.MENTOR)
@ApiResponse({ type: TrackDto, status: HttpStatus.CREATED })
@ApiResponse({ status: HttpStatus.FORBIDDEN, type: ApiException })
@UseInterceptors(FileInterceptor('thumbnail'))
@ApiConsumes('multipart/form-data')
@ApiBearerAuth()
async createTrack(
@Body() input: CreateWithThumbnailTrackDto,
@UploadedFile() thumbnail: BufferedFile,
@Req() req: Request
): Promise<TrackDto> {
if (!thumbnail)
throw new BadRequestException('Thumbnail image cannot be empty');
if (thumbnail.mimetype.split('/')[0] !== 'image')
throw new UnsupportedMediaTypeException('File is not an image');
if (thumbnail.size / ONE_KB > 200)
throw new BadRequestException('File cannot be larger than 200KB');
const exist = await this.trackService.findOneAsync({
title: input.title.toUpperCase()
});
if (exist)
throw new ConflictException(
`Track with the title "${exist.title}" already exists`
);
const userId = req.user['userId'];
const thumbnailUrl = await uploadFileToCloud(thumbnail, 'avatars', userId);
const dto = input as any;
dto.thumbnailUrl = thumbnailUrl;
delete dto.thumbnail;
return await super.create(dto);
}
Example #6
Source File: MediaController.ts From typescript-clean-architecture with MIT License | 6 votes |
@Post()
@HttpAuth(UserRole.ADMIN, UserRole.AUTHOR)
@HttpCode(HttpStatus.OK)
@UseInterceptors(FileInterceptor('file'))
@ApiBearerAuth()
@ApiConsumes('multipart/form-data')
@ApiBody({type: HttpRestApiModelCreateMediaBody})
@ApiQuery({name: 'name', type: 'string', required: false})
@ApiQuery({name: 'type', enum: MediaType})
@ApiResponse({status: HttpStatus.OK, type: HttpRestApiResponseMedia})
public async createMedia(
@Req() request: HttpRequestWithUser,
@UploadedFile() file: MulterFile,
@Query() query: HttpRestApiModelCreateMediaQuery
): Promise<CoreApiResponse<MediaUseCaseDto>> {
const adapter: CreateMediaAdapter = await CreateMediaAdapter.new({
executorId: request.user.id,
name : query.name || parse(file.originalname).name,
type : query.type,
file : file.buffer,
});
const createdMedia: MediaUseCaseDto = await this.createMediaUseCase.execute(adapter);
this.setFileStorageBasePath([createdMedia]);
return CoreApiResponse.success(createdMedia);
}
Example #7
Source File: storage.controller.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
@Post()
@HttpCode(204)
@UseInterceptors(FileInterceptor('file'))
@Permissions('storage/upload')
public async upload(
@Query('dir') dir = '',
@UploadedFile() file: any
): Promise<void> {
const tenant = await this.tenantService.findOne();
const StorageClient = this.storageLoader.load(tenant.settings.storageMedium || 'fs');
const client = new StorageClient(tenant.settings.storageConfig);
await client.init();
return await client.put(`${dir}/${file.originalname}`.replace(/^(\/uploads)/, '').replace(/^\//, ''), file.buffer);
}
Example #8
Source File: app.controller.ts From gear-js with GNU General Public License v3.0 | 5 votes |
@Post('build')
@UseInterceptors(FileInterceptor('file'))
async build(@UploadedFile() file) {
const id = generateId();
const path = unpackZip(file.buffer, id);
this.appService.processBuild(path, id);
return { id: id };
}
Example #9
Source File: profile.controller.ts From office-hours with GNU General Public License v3.0 | 5 votes |
@Post('/upload_picture')
@UseInterceptors(
FileInterceptor('file', {
storage: memoryStorage(),
}),
)
async uploadImage(
@UploadedFile() file: Express.Multer.File,
@User() user: UserModel,
): Promise<void> {
if (user.photoURL) {
fs.unlink(process.env.UPLOAD_LOCATION + '/' + user.photoURL, (err) => {
console.error(
'Error deleting previous picture at: ',
user.photoURL,
err,
'the previous image was at an invalid location?',
);
});
}
const spaceLeft = await checkDiskSpace(path.parse(process.cwd()).root);
if (spaceLeft.free < 1000000000) {
// if less than a gigabyte left
throw new ServiceUnavailableException(
ERROR_MESSAGES.profileController.noDiskSpace,
);
}
const fileName =
user.id +
'-' +
Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15);
await sharp(file.buffer)
.resize(256)
.toFile(path.join(process.env.UPLOAD_LOCATION, fileName));
user.photoURL = fileName;
await user.save();
}