Uploading a buffer to google cloud storage

后端 未结 4 609
无人及你
无人及你 2021-02-07 06:27

I\'m trying to save a Buffer (of a file uploaded from a form) to Google Cloud storage, but it seems like the Google Node SDK only allows files with a given path to be uploaded (

4条回答
  •  灰色年华
    2021-02-07 07:06

    The following snippet is from a google example. The example assumes you have used multer, or something similar, and can access the file at req.file. You can stream the file to cloud storage using middleware that resembles the following:

    function sendUploadToGCS (req, res, next) {
      if (!req.file) {
        return next();
      }
    
      const gcsname = Date.now() + req.file.originalname;
      const file = bucket.file(gcsname);
    
      const stream = file.createWriteStream({
        metadata: {
          contentType: req.file.mimetype
        },
        resumable: false
      });
    
      stream.on('error', (err) => {
        req.file.cloudStorageError = err;
        next(err);
      });
    
      stream.on('finish', () => {
        req.file.cloudStorageObject = gcsname;
        file.makePublic().then(() => {
          req.file.cloudStoragePublicUrl = getPublicUrl(gcsname);
          next();
        });
      });
    
      stream.end(req.file.buffer);
    }
    

提交回复
热议问题