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);
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With