How do I upload a base64 encoded image (string) directly to a Google Cloud Storage bucket using Node.js?

前端 未结 6 1740
野性不改
野性不改 2020-11-30 04:51

Currently, I am using the @google-cloud/storage NPM package to upload a file directly to a Google Cloud Storage bucket. This requires some trickery as I only have the image\

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 05:05

    You have to convert base64 to image buffer then upload as below, you need to provide image_data_from_html variable as the data you extract from HTML event.

    const base64Text = image_data_from_html.split(';base64,').pop();
    const imageBuffer = Buffer.from(base64Text, 'base64');
    const contentType = data.image_data.split(';base64,')[0].split(':')[1];
    const fileName = 'myimage.png';
    const imageUrl = 'https://storage.googleapis.com/bucket-url/some_path/' + fileName;
    
    await admin.storage().bucket().file('some_path/' + fileName).save(imageBuffer, {
        public: true,
        gzip: true,
        metadata: {
            contentType,
            cacheControl: 'public, max-age=31536000',
        }
    });
    
    console.log(imageUrl);
    

提交回复
热议问题