Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload JSON string to Google Cloud Storage without a file

My case is when I receive data from some other source as a JSON string, then I want to upload this string to Google Cloud Storage without writing this string to a local file and upload this file. Is there any way to do this. Thank you. Look like this code below

storage
  .bucket(bucketName)
  .upload(jsonString, { destination: 'folder/test.json' })
  .then(() => {
    console.log('success');
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

so I expected the Google Cloud Storage will have a file test.json with content from the jsonString

like image 223
Quoc Van Tang Avatar asked Aug 03 '18 07:08

Quoc Van Tang


People also ask

How do I upload data to Google Cloud Storage?

Drag and drop the desired files from your desktop or file manager to the main pane in the Google Cloud console. Click the Upload Files button, select the files you want to upload in the dialog that appears, and click Open.

Can I upload files to Google Cloud Storage from URL?

Cloud Storage provides the Signed URL feature to let individual end users perform specific actions. Signed URL makes it possible to generate temporary credentials valid only for a specific end user to securely upload a file. The Google Cloud official client library makes it easy to generate a Signed URL.


2 Answers

It looks like this scenario has already been addressed in this other question.

Both answers look good, but it will probably be easier to use the file.save() method (second answer).You can find the description of this method and yet another example here.

Hope this helps.

like image 104
ch_mike Avatar answered Oct 20 '22 00:10

ch_mike


In case some one is looking for the snippet of the answer here it is using the file.save(). Please do note that the data should be stringfy.

const storage = new Storage();

exports.entry_point = (event, context) => {
  var data = Buffer.from(event.data, 'base64').toString();
  data = transform(data)
  var datetime = new Date().toISOString()
  var bucketName =  storage.bucket('your_filename')
  var fileName = bucketName.file(`date-${datetime}.json`)
  fileName.save(data, function(err) {
  if (!err) {
    console.log(`Successfully uploaded ${fileName}`)
  }});

  //-
  // If the callback is omitted, we'll return a Promise.
  //-
  fileName.save(data).then(function() {});
};
like image 34
Joshua Abad Avatar answered Oct 20 '22 00:10

Joshua Abad