dmitriy-nz / nestjs-form-data

NestJS middleware for handling multipart/form-data, which is primarily used for uploading files.
https://www.npmjs.com/package/nestjs-form-data
MIT License
118 stars 23 forks source link

Can I configure filename and path like this with this plugin? #6

Closed talski closed 3 years ago

talski commented 3 years ago
@UseInterceptors(
  FilesInterceptor('attachments', null, {
    storage: diskStorage({
      destination: function(req, file, cb) {
        const user = req.user as User;

        const path = `./attachments/${user.tenant}/questions/${req.params.id}/answers/${user.id}/`;
        fs.mkdirSync(path, { recursive: true });
        cb(null, path);
      },
      filename: (_req, file, cb) => {
        return cb(null, `${uuid()}-${file.originalname}`);
      }
    })
  })
)
dmitriy-nz commented 3 years ago

Hi, you can use wild storage and temporary directory, then in the controller move the file to the permanent storage directory

  @Post('load')
  @FormDataRequest({ storage: FileSystemStoredFile })
  async getHello(@Body() attachmentsDto: AttachmentsDto, @Param() params: any, @Req() req): Promise<void> {
    const user = req.user as User;
    const storageDirPath = path.resolve(__dirname, 'attachments', user.tenant, 'questions', params.id, 'answers', user.id);

    for (let file of attachmentsDto.attachments) {
      fs.mkdirSync(storageDirPath, { recursive: true });
      /** move file from temp folder to the permanent storage directory **/
      fs.renameSync(file.path, path.resolve(storageDirPath, `${uuid()}-${file.originalName}`));
    }

  }