在nestjs中使用multer-gridfs流

问题描述 投票:0回答:1

我试图明确地在nestjs中使用multer-gridfs-storage中间件。我想存储一个文件并使用gridfs-stream包检索它。但没有什么对我有用。我无法获得填充文件本身的请求。每当我尝试打印请求对象时,它都没有与req.file或buffer元素相关的任何内容。我不确定如何使用multer获取文件后如何处理文件。

这是样本控制器方法

@Post('/uploadFiles')
    public async postFileToMongo(@Req() req, @Res() res) {

        //logger.info('this is the mutler upload details',req.body);
        //logger.info('coming inside upload files', req);
        logger.info('this is the sample value set');
        logger.info('this is the request body', req);
        logger.info('this is the request files', req.file);
        await this.fileStorageService.createFilesIntoGridFsUsingGridFSStream();
        res.send('Done');
    }

这是FileStorageService。我还没有实现multerStorage,因为我从控制器中得不到任何东西(req.file为空)

 @Injectable()
    export class FileStorageService {
      mongooseConnection: mongoose.Connection;
      gridfsConnection: GridFsStream.Grid;
      gridfsStorage: GridFSStorage;
      uploadStorage;
      constructor(
        @Inject(MONGO_DB_PROVIDER_TOKEN_TEST) private readonly mongoCon: Connection,
        private readonly configService : ConfigProviderService,
      ) {
        this.mongooseConnection = this.mongoCon as mongoose.Connection;

     this.gridfsConnection = GridFsStream(
            this.mongooseConnection.db,
            mongoose.mongo,
          );
        this.gridfsConnection.collection('default_collection');
          // now intialize the storage engine

        this.gridfsStorage = new GridFSStorage({
          db: this.mongooseConnection,
          cache: true,
          file: (req, file) => {

            // instead of just returning fileName or bucket Name as below
            // we could return an object 
            // let bucket;
            // if (file.mimetype === 'multipart/*' || file.mimetype === 'img/jpeg') {
            //   bucket = 'first_collection';
            // } else {
            //   bucket = 'second_collection';
            // }
            return {
              filename: file.originalname + Date.now(),
              bucketName: 'default_collection',
            }
          },
        });
        this.uploadStorage = multer({ storage: this.gridfsStorage });


        logger.info('gridfsConnection obj', isNullOrUndefined(this.gridfsConnection));
        //logger.info('upload storage vale', this.uploadStorage);
      }

    async createFilesIntoGridFsUsingGridFSStream() {
        //console.log(this.uploadStorage);
       const writeStream  =  this.gridfsConnection.createWriteStream({
            filename: 'doodle_test.png',
            mode: 'w',
            root: 'first_collect',
            chunkSize: 1024,
            metadata: {
              file_desc: 'This is a sample metadata added',
            },
        });
       const filestring = path.resolve('./doodle.png');
       await fs.createReadStream(filestring).pipe(writeStream).on('error', err => {
          logger.info('err ob', err);
        });
       writeStream.on('close', (file) => {
          logger.info('file name is', file.filename);
        });
      }

      async createFilesUsingMulter(req, ){

      }


    }

我甚至尝试创建一个单独的中间件,但它也没有用

@Injectable()
export class FileStorageMiddlewareMiddleware implements NestMiddleware {
  mongooseConnection: Connection;
  constructor(@Inject(MONGO_DB_PROVIDER_TOKEN_TEST) private readonly mongoConnection: Connection,
              private readonly configService: ConfigProviderService){
    this.mongooseConnection = this.mongoConnection as mongoose.Connection;
  }
  resolve(...args: any[]): MiddlewareFunction {
    return (req, res, next) => {
      logger.info('inside file storage middleware');
      // const fileStorage = new multerGridfsStorage({
      //   // url: this.configService.getDBCred().$urlString,
      //   db: this.mongoConnection as Connection,
      //   cache: true,
      //   file :(req, file) => {
      //     //determine the default filename
      //     const filename = file.filename+'feedback_file_'+Date.now();
      //     let bucketname = 'default_file_collection';
      //     if(file.mimetype === 'plain/text') {
      //       bucketname = 'files.text';
      //     } else if(file.mimetype === 'plain/html'){
      //       bucketname = 'files.html'; 
      //     } else if(file.mimetype === 'img/png' || file.mimetype === 'img/jpeg' ||
      //       file.mimetype === 'img.jpg'){
      //       bucketname = 'files.image';
      //     }

      //     return {fileName: filename, bucketName: bucketname};
      //     // determing the bucketname
      //   },
      // });
      // const upload = multer({storage: fileStorage});

      // //upload.single('./../../../src/fileUpload');
      // //busboyBodyParser({ limit: '1kb' }, { multi: true });
      // // req.busboyBodyParser([{limit: '20mb'}, {multi: true}]);
      // upload.single('file');
      next();
    };
  }
}

注意:我包含了中间件并在模块中使用它。我能够看到中间件中的日志,但不能看到多形式零件数据

以下是'postman'工具的详细信息(使用3002作为端口,'development'作为上下文路径

enter image description here

这是我使用gridfs-stream模块执行的过程,从本地文件夹获取示例文件并将其存储在gridfs中并且工作正常。

   async createFilesIntoGridFsUsingGridFSStream() {
this.gridfsConnection = GridFsStream(
            this.mongooseConnection.db,
            mongoose.mongo,
          );
        //console.log(this.uploadStorage);
       const writeStream  =  this.gridfsConnection.createWriteStream({
            filename: 'doodle_test.png',
            mode: 'w',
            root: 'first_collect',
            chunkSize: 1024,
            metadata: {
              file_desc: 'This is a sample metadata added',
            },
        });
       const filestring = path.resolve('./doodle.png');
       await fs.createReadStream(filestring).pipe(writeStream).on('error', err => {
          logger.info('err ob', err);
        });
       writeStream.on('close', (file) => {
          logger.info('file name is', file.filename);
        });
      }

但有一个警告我认为gridfs默认使用GridStore并尝试将其存储在一个集合中

DeprecationWarning:GridStore已弃用,将在未来版本中删除。请改用GridFSBucket(node:29332)DeprecationWarning:不推荐使用collection.ensureIndex。请改用createIndexes。 (node:29332)DeprecationWarning:不推荐使用collection.save。请改用insertOne,insertMany,updateOne或updateMany。

因此,想要使用multer-gridfs-storage,它默认使用GridFSStorage

以防万一,这是版本细节

"@types/mongoose": "^5.3.20",
    "@types/multer": "^1.3.7",
    "@types/multer-gridfs-storage": "^3.1.1", "gridfs": "^1.0.0",
    "gridfs-stream": "^1.1.1",  "mongoose": "^5.4.11",
    "multer": "^1.4.1",
    "multer-gridfs-storage": "^3.2.3",

编辑:这是出于学习目的,并希望深入了解如何在nestjs中处理快速中间件。我知道nestjs有类似FileInterceptor的东西来处理文件,但想获得更多关于此的信息

另外我想问一下multer-gridfs-storage如何使用gridfs-stream存储文件,是否有任何条款提供multer-gridfs-storage应该使用哪种流?

mongoose nestjs multer-gridfs-storage
1个回答
0
投票

在这里你去这个视频教程将帮助你Uploading Files to MongoDB With GridFS (Node.js App) by Brad Traversy

© www.soinside.com 2019 - 2024. All rights reserved.