Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading a buffer to google cloud storage

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 (Read / Write streams).

This is what I have used for AWS (S3) - is the anything else similar in the Google node SDK?:

var fileContents = new Buffer('buffer');

var params = {
  Bucket: //bucket name
  Key: //file name
  ContentType: // Set mimetype
  Body: fileContents 
};

s3.putObject(params, function(err, data) {
// Do something 
});

The only way that I have found to do it so far is write the buffer to disk, upload the file using the SDK (specifying the path to the new file) and then delete the file once it's uploaded successfully - the downside to this is that the whole process is significantly slower, to where it seems to be unfeasible to use Google storage. Is there any work around / way to upload a buffer?

like image 793
Ash Avatar asked Apr 10 '16 20:04

Ash


People also ask

How do I upload data to Google Cloud Storage?

In the Google Cloud console, go to the Cloud Storage Buckets page. In the list of buckets, click on the name of the bucket that you want to upload an object to. In the Objects tab for the bucket, either: Drag and drop the desired files from your desktop or file manager to the main pane in the console.

How do I import a CSV file into Google Cloud Storage?

Select All Settings > Raw Data Export > CSV Upload. Select Google Cloud Storage from the dropdown menu. Upload your Service Account Key credential file. This is the JSON file created in the Google Cloud Console. Enter your Google Cloud Storage bucket name.

How do I upload a folder to Google Cloud using Python?

def upload_files(bucketName): """Upload files to GCP bucket.""" files = [f for f in listdir(localFolder) if isfile(join(localFolder, f))] for file in files: localFile = localFolder + file blob = bucket. blob(bucketFolder + file) blob. upload_from_filename(localFile) return f'Uploaded {files} to "{bucketName}" bucket.


Video Answer


4 Answers

.save to save the day! Some code below where I save my "pdf" that I created.

https://googleapis.dev/nodejs/storage/latest/File.html#save

const { Storage } = require("@google-cloud/storage");

const gc = new Storage({
  keyFilename: path.join(__dirname, "./path to your service account .json"),
  projectId: "your project id",
});

      const file = gc.bucket(bucketName).file("tester.pdf");
      file.save(pdf, (err) => {
        if (!err) {
          console.log("cool");
        } else {
          console.log("error " + err);
        }
      });
like image 80
Nick Foden Avatar answered Oct 26 '22 05:10

Nick Foden


This is actually easy:

  let remotePath = 'some/key/to/store.json';
  let localReadStream = new stream.PassThrough();
  localReadStream.end(JSON.stringify(someObject, null, '   '));

  let remoteWriteStream = bucket.file(remotePath).createWriteStream({ 
     metadata : { 
        contentType : 'application/json' 
     }
  });

  localReadStream.pipe(remoteWriteStream)
  .on('error', err => {
     return callback(err);      
  })
  .on('finish', () => {
     return callback();
  });
like image 41
Hoovinator Avatar answered Oct 26 '22 04:10

Hoovinator


We have an issue about supporting this more easily: https://github.com/GoogleCloudPlatform/gcloud-node/issues/1179

But for now, you can try:

file.createWriteStream()
  .on('error', function(err) {})
  .on('finish', function() {})
  .end(fileContents);
like image 8
Stephen Avatar answered Oct 26 '22 03:10

Stephen


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);
}
like image 5
Geige V Avatar answered Oct 26 '22 03:10

Geige V