Skip to content

Commit 7066695

Browse files
committed
Added right file extensions and names on upload
1 parent af010bb commit 7066695

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

nest-file-uploading/.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# compiled output
22
/dist
33
/node_modules
4+
/files
45

56
# Logs
67
logs
Binary file not shown.

nest-file-uploading/src/app.controller.ts

+15-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { Controller, Get, Post, UseInterceptors, UploadedFile, UploadedFiles, Res, Param } from '@nestjs/common';
22
import { AppService } from './app.service';
3-
import { FilesInterceptor } from '@nestjs/platform-express';
3+
import { FileInterceptor } from '@nestjs/platform-express';
4+
import { diskStorage } from 'multer';
5+
import { extname } from 'path';
46

57
@Controller()
68
export class AppController {
@@ -12,9 +14,19 @@ export class AppController {
1214
}
1315

1416
@Post()
15-
@UseInterceptors(FilesInterceptor('image'))
17+
@UseInterceptors(FileInterceptor('image', {
18+
storage: diskStorage({
19+
destination: './files'
20+
, filename: (req, file, cb) => {
21+
const name = file.originalname.split('.')[0];
22+
const fileExtName = extname(file.originalname);
23+
const randomName = Array(4).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('');
24+
cb(null, `${name}-${randomName}${fileExtName}`);
25+
},
26+
}),
27+
}))
1628
UploadedFile(@UploadedFiles() file) {
17-
console.log(file);
29+
// console.log(file);
1830
}
1931

2032
@Get(':imgpath')

0 commit comments

Comments
 (0)