我如何从环回 4 上传到 MongoDB GridFS

Posted

技术标签:

【中文标题】我如何从环回 4 上传到 MongoDB GridFS【英文标题】:How can i upload to MongoDB GridFS from loopback 4 【发布时间】:2021-11-24 09:53:00 【问题描述】:

我是 Loopback 4 的新手。我正在尝试使用 loopback 4 将文件上传到 MongoDB GridFS。 我使用了 Loopback 4 示例中的文件上传示例,但理解不够,无法对其进行修改?

protected configureFileUpload(destination?: string) 
    const url = 'mongodb://' + MongoDataSource.defaultConfig.user + ':' +
      MongoDataSource.defaultConfig.password
      + '@' + MongoDataSource.defaultConfig.host +
      ':' + MongoDataSource.defaultConfig.port +
      '/' + MongoDataSource.defaultConfig.database;
    const conn = mongoose.createConnection(url);
    let gfs;
    conn.once('open', () => 
      gfs = Grid(conn.db, mongoose.mongo);
      gfs.collection('uploads');
    );

    const storage = new GridFsStorage(
      url: url,
      file: (req: any, file: any) => 
        return new Promise((resolve, reject) => 
          //crypto create a unique id for the file to be uploaded
          crypto.randomBytes(16, (err, buf) => 
            if (err) return reject(err);
            const filename = buf.toString('hex') + path.extname(file.originalname);
            const fileInfo = 
              filename: filename,
              bucketName: 'bucketName',
              metadata: 
                originalName: file.originalname,
                encoding: file.encoding,
                mimetype: file.mimetype,
                size: file.size,
                expires: Date.now() + 1000 * 60 * 60
              
            
            resolve(fileInfo)
          )
        );
      
    );
    storage;

    return multer(storage: storage).any();
  

【问题讨论】:

【参考方案1】:

这就是我解决自己问题的方法

import inject from '@loopback/core';
import 
  repository
 from '@loopback/repository';
import 
  getModelSchemaRef,
  post,
  Request,
  requestBody,
  Response,
  response,
  RestBindings
 from '@loopback/rest';
import crypto from 'crypto';
import multer from 'multer';
import GridFsStorage from 'multer-gridfs-storage';
import path from 'path';
import MongoDataSource from '../datasources';
import FILE_UPLOAD_SERVICE from '../keys';
import Gridfs from '../models';
import GridfsRepository from '../repositories';
import FileUploadHandler from '../types';

const url = 'mongodb://' + MongoDataSource.defaultConfig.user +
  ':' + MongoDataSource.defaultConfig.password +
  '@' + MongoDataSource.defaultConfig.host +
  ':' + MongoDataSource.defaultConfig.port +
  '/' + MongoDataSource.defaultConfig.database;

var storage = new GridFsStorage(
  url: url,
  file: (req: any, file: any) => 
    return new Promise((resolve, reject) => 
      //crypto create a unique id for the file to be uploaded
      crypto.randomBytes(16, (err, buf) => 
        if (err) return reject(err);
        const filename = buf.toString('hex') + path.extname(file.originalname);
        const fileInfo = 
          filename: filename,
          bucketName: 'documents',
          metadata: 
            originalName: file.originalname,
            encoding: file.encoding,
            mimetype: file.mimetype,
            size: file.size,
            expires: Date.now() + 1000 * 60 * 60
          
        
        return resolve(fileInfo)
      )
    );
  
);
const upload = multer(storage);

export class GridfsController 
  constructor(
    @repository(GridfsRepository)
    public gridfsRepository: GridfsRepository,
    @inject(FILE_UPLOAD_SERVICE) private handler: FileUploadHandler,
  ) 
    console.log(FILE_UPLOAD_SERVICE);
    console.log(handler);
  

  @post('/gridfs')
  @response(200, 
    description: 'Tender model instance',
    content: 'multipart/form-data': schema: getModelSchemaRef(Gridfs),
  )
  async create(
    @requestBody(
      content: 
        'multipart/form-data': 
          schema: getModelSchemaRef(Gridfs, 
            title: 'NewGridfs',
            exclude: ['id'],
          ),
        ,
      ,
    )
    gridfs: Omit<Gridfs, 'id'>,
  ): Promise<Gridfs> 
    return this.gridfsRepository.create(gridfs);
  

  @post('/files', 
    responses: 
      200: 
        content: 
          'application/json': 
            schema: 
              type: 'object',
            ,
          ,
        ,
        description: 'Files and fields',
      ,
    ,
  )
  async fileUpload(
    @requestBody.file()
    request: Request,
    @inject(RestBindings.Http.RESPONSE) response: Response,
  ): Promise<object> 
    return new Promise<object>((resolve, reject) => 
      upload.single('file')(request, response, err => 
        if (err) return reject(err);
        let file = request.file as any;
        resolve(
          id: file.id.toString(),
          originalName: file.originalname,
          encoding: file.encoding,
          mimetype: file.mimetype,
          size: file.size,
          expires: Date.now() + 1000 * 60 * 60
        );
      );
    );
  

显然这很容易

【讨论】:

以上是关于我如何从环回 4 上传到 MongoDB GridFS的主要内容,如果未能解决你的问题,请参考以下文章

环回 3 文件存储连接器

Selenium Grid:“找不到此机器的非环回 ip4 地址”和“发生了非法反射访问操作”

来自环回的 mongodb 中格式为 yyyy--mm-dd 的字符串日期上的 gte

如何从环聊按钮获取环聊网址

如何使用 openapi-to-graphql 在环回 4 中启用 graphql 订阅

如何使用nestJS将文件上传到mongoose上的mongodb?