Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload a file to Google Cloud, in a specific directory

Tags:

How to upload a file on Google Cloud, in a specific bucket directory (e.g. foo)?

"use strict";  const gcloud = require("gcloud");  const PROJECT_ID = "<project-id>";  let storage = gcloud.storage({   projectId: PROJECT_ID,   keyFilename: 'auth.json' });  let bucket = storage.bucket(`${PROJECT_ID}.appspot.com`) bucket.upload("1.jpg", (err, file) => {     if (err) { return console.error(err); }     let publicUrl = `https://firebasestorage.googleapis.com/v0/b/${PROJECT_ID}.appspot.com/o/${file.metadata.name}?alt=media`;     console.log(publicUrl); }); 

I tried:

bucket.file("foo/1.jpg").upload("1.jpg", ...) 

But there's no upload method there.

How can I send 1.jpg in the foo directory?

In Firebase, on the client side, I do:

ref.child("foo").put(myFile); 
like image 547
Ionică Bizău Avatar asked Oct 21 '16 12:10

Ionică Bizău


People also ask

Can I upload files to Google Cloud Storage from URL?

Uploading files using Signed URL Now, a user can upload files directly to Cloud Storage using Signed URLs dispatched in the above way. Here, we'll use PUT Object , one of the Cloud Storage XML APIs, for the Signed URL that App Engine has generated.


2 Answers

bucket.upload("1.jpg", { destination: "YOUR_FOLDER_NAME_HERE/1.jpg" }, (err, file) => {     //Do something... }); 

This will put 1.jpg in the YOUR_FOLDER_NAME_HERE-folder.

Here is the documentation. By the way, gcloud is deprecated and you should use google-cloud instead.

like image 196
robbannn Avatar answered Sep 28 '22 08:09

robbannn


UPDATE 2020

according to google documentation:

const { Storage } = require('@google-cloud/storage'); const storage = new Storage() const bucket = storage.bucket('YOUR_GCLOUD_STORAGE_BUCKET') const blob = bucket.file('youFolder/' + 'youFileName.jpg')  const blobStream = blob.createWriteStream({     resumable: false,     gzip: true,     public: true })  blobStream.on('error', (err) => {     console.log('Error blobStream: ',err) });  blobStream.on('finish', () => { // The public URL can be used to directly access the file via HTTP.     const publicUrl = ('https://storage.googleapis.com/'+ bucket.name + '/' + blob.name)     res.status(200).send(publicUrl); });  blobStream.end(req.file.buffer)//req.file is your original file 
like image 43
Álvaro Agüero Avatar answered Sep 28 '22 08:09

Álvaro Agüero