简体   繁体   中英

How to upload an image from an external link to google cloud storage?

I am using google-cloud-storage on Node.js . Trying to find a solution to programmatically download an image from an external url then upload to GCS.

I'm using fetch API to get the image and turn it into a blob

fetch('image.jpg').then( res => {
    var blob = res.blob()
}) 

All tutorials I've found on the web deal with form upload using multer. But nothing about my case.

Now what's the right solution to upload this blob on my GCS bucket ?

EDIT : I've also tried this, without success

bucket.upload(urlImage, function(err, file){
            const blobStream = file.createWriteStream();
            blobStream.on('error', (err) => {
              console.log('error',err)
            });

            blobStream.on('finish', () => {
              console.log('finished with success')

              });

              blobStream.end(file);
          })

Try using the request module for Node.js to obtain the image from the URL and pipe the result to be written into the bucket:

var request = require('request');

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('your-bucket-name');
const file = bucket.file('image-name.jpg'); 

request(‘image-URL’).pipe(file.createWriteStream());

It worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM