Ionică Bizău
Ionică Bizău

Reputation: 113335

Upload a file to Google Cloud, in a specific directory

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

Upvotes: 23

Views: 17089

Answers (8)

Eyobed kebede
Eyobed kebede

Reputation: 1

UPDATE 2023

You can do file uploads to a specific directory using the bellow code:

// choose the bucket to be used
const bucket = storage.bucket("bucket_name");

// check if there is an image
if (!req.file) {
  return next(new AppError("Please upload a file!", 400));
}

// Create a new blob in the bucket and upload the file data.
const blob = bucket.file('foo/'+req.file.originalname);

// save the bolb/GCP object properties 
await blob.save();

//write to the blob
const blobStream = blob.createWriteStream({
  resumable: false,
});

blobStream.on("error", (err) => {
  return next(new AppError(err.message, 400));
});


blobStream.on("finish", async (_) => {

  // make the current objects public
  await blob.makePublic();

  // Create URL for directly accessing the file.
  const publicUrl = `https://storage.googleapis.com/${bucket.name}/foo/${req.file.originalname}`;

  data.image = publicUrl;

// Insert the new data to database
const userData = await ModelRepo.addNewData(data);

//response
res.status(200).json({
  successs: true,
  data: { user: userData },
});
});
// end the processes of the write streams
blobStream.end(fs.readFileSync(req.file.path));

Upvotes: 0

Amit Sharma
Amit Sharma

Reputation: 163

To upload inside specific directory in .NET Core, use

var uploadResponse= await storageClient.UploadObjectAsync(bucketName, $"{foldername}/"+fileName, null, memoryStream);

This should upload your file 'fileName' inside folder 'foldername' in the bucket

Upvotes: 1

&#193;lvaro Ag&#252;ero
&#193;lvaro Ag&#252;ero

Reputation: 4800

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

Upvotes: 7

Praveen G
Praveen G

Reputation: 984

If you want to use async-await while uploading files into storage buckets the callbacks won't do the job, Here's how I did it.

async function uploadFile() {
    const destPath = 'PATH_TO_STORAGE/filename.extension';

    await storage.bucket("PATH_TO_YOUR_BUCKET").upload(newFilePath, {
        gzip: true,
        destination: destPath,  
    });
}

Hope it helps someone!

Upvotes: 0

Bira
Bira

Reputation: 5506

Here you go...

const options = {
  destination: 'folder/new-image.png',
  resumable: true,
  validation: 'crc32c',
  metadata: {
    metadata: {
      event: 'Fall trip to the zoo'
    }
  }
};

bucket.upload('local-image.png', options, function(err, file) {
  // Your bucket now contains:
  // - "new-image.png" (with the contents of `local-image.png')

  // `file` is an instance of a File object that refers to your new file.
});

Upvotes: 3

Prem Sanil
Prem Sanil

Reputation: 128

If accessing from the same project projectId , keyFilename,.. not required,I use the below code for both upload and download , it works fine.

// Imports the Google Cloud client library
const Storage = require('@google-cloud/storage');
const storage = new Storage();
var destFilename = "./test";
var bucketName = 'cloudtesla';
var srcFilename = 'test';

  const options = {
    destination: destFilename,
  };


//upload file
console.log("upload Started");
storage.bucket(bucketName).upload(srcFilename, {}, (err, file) => {

        if(!err)
        console.log("upload Completed");
        else
        console.log(err);
});


//Download file
console.log("Download Started");
  storage
    .bucket(bucketName)
    .file(srcFilename)
    .download(options)
    .then(() => {
      console.log("Download Completed");
    })
    .catch(err => {
      console.error('ERROR:', err);
    });

Upvotes: 1

robbannn
robbannn

Reputation: 5013

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.

Upvotes: 34

Matt J
Matt J

Reputation: 431

I think just adding foo/ to the filename should work, like bucket.upload("foo/1.jpg", (err, file) ... In GCS, directories just a matter of having a '/' in the file name.

Upvotes: 0

Related Questions