Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

node.js - Manage uploaded image in nest js

I use multer to manage uploaded file:

@Post('upload') @UseInterceptors(FilesInterceptor("images", 10, {
  dest: "./uploads",
}))
uploadMultiple(@UploadedFiles() files) {
  console.log(files, 'test');
}

I try to add a file extension to my uploaded files as:

@Post('upload') @UseInterceptors(FilesInterceptor("images", 10, {
  dest: "./uploads",
   filename: function (req, file, cb) {
    cb(null, Date.now() + '.jpg') //Appending .jpg
  }
}))

But when I do this I get an error:

TS2345: Argument of type '{ dest: string; filename: (req: any, file: any, cb: any) => void; }' is not assignable to parameter of type 'MulterOptions'. ??Object literal may only specify known properties, and 'filename' does not exist in type 'MulterOptions'

How to specify file extension to my uploaded files?

question from:https://stackoverflow.com/questions/65891450/manage-uploaded-image-in-nest-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it dynamically using the extname import from path using the diskStorage to get your filename extension.

import { extname } from 'path';
import { diskStorage } from 'multer';

export const exampleDiskStorage = diskStorage({
  destination: './public/img/users',
  filename: (req, file, cb) => {
    return cb(null, `${Date.now()}${extname(file.originalname)}`);
  }
});

In your module, you only need to import the diskStorage to MulterModule.register

import { MulterModule } from '@nestjs/platform-express';

@Module({
  imports: [
    MulterModule.register({
      storage: exampleDiskStorage,
    }),
  ],
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...