I want to upload a google cloud storage image to a third-party API using nodejs.
I tried to upload a local disk image to third-party API, it’s working fine, and I tried cloud storage image write to the local disk, it’s also working fine. But when I try to read cloud storage images and add them to third-party API, it's not working.
var fs = require('fs');
const request = require("request-promise");
async function uploadToWeChat(token){
// this code is working fine
const options = {
method: "POST",
url: `https://cors-anywhere-xbtfslevmq-km.a.run.app/https://api.weixin.qq.com/cgi-bin/media/upload?access_token=${token}&type=image`,
headers: {
"Content-Type": "multipart/form-data"
},
formData: {
"image" : fs.createReadStream("temp.jpg") //upload image on localdisk
}
};
return await request(options, function (err, res, body) {
if(err) console.log(err);
});
}
But when I am trying to upload a google cloud storage image, it's not working.
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('mybucket');
const file = myBucket.file('tempImg.jpg');
const request = require("request-promise");
async function uploadToWeChat(token){
//not working
const options = {
method: "POST",
url: `https://cors-anywhere-xbtfslevmq-km.a.run.app/https://api.weixin.qq.com/cgi-bin/media/upload?access_token=${token}&type=image`,
headers: {
"Content-Type": "multipart/form-data"
},
formData: {
"image" : file.createReadStream() //read stream of google cloud storage image
}
};
return await request(options, function (err, res, body) {
if(err) console.log(err);
});
}
I tried to access google cloud storage images and write to a local disk. It's working fine.
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('mybucket');
const file = myBucket.file('tempImg.jpg');
var fs = require('fs');
const readStream = file.createReadStream()
var newfile = fs.createWriteStream("tempImg.jpg"); // working fine
readStream.pipe(newfile);