Upload a file to Google Cloud, in a specific directory

Ionică Bizău picture Ionică Bizău · Oct 21, 2016 · Viewed 9.8k times · Source

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);

Answer

robbannn picture robbannn · Mar 22, 2017
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.