Search code examples
node.jsazureazure-devopsnode-modulesmonodevelop

error in uploading base64Image to azure storage by using nodejs


I am getting an error when uploading a base64Image to Azure.

Code with Node.js:

var name = req.body.name;
var img = req.body.image; //this image is base64Image

var uploadOptions = {
    container: 'myphoto',
    blob: name,
    text: img
}

blobServiceClient.createBlockBlobFromText(
    uploadOptions.container,
    uploadOptions.blob,
    uploadOptions.text,
    {
        contentType: 'image/jpg',
        contentEncoding: 'base64'
    }, 
    function(error, result, response) {
        if (error) {
            res.send(error);
        }

        console.log("result", result);
    
        console.log("response", response);
    }
);    

This is the image in Azure: the result that I got in Azure

and this is the error I get when I open the image: the error that I got when I opened the image

The requested image is in base64Image formatting.

How can I fix this error?


Solution

  • If you upload base64 image to azure blob storage, I suggest you convert the image content to Buffer then upload it.

    For example

    My Base64 image

    data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUTExMWFRUXGBobGBgYGRsfIBoZIBsgHSAgIB0ZISghGR0lGx0XIT....
    
    1. Code
    var name = req.body.name;
    var img = req.body.image; //this image is base64Image
    var matches = img.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
    var type = matches[1];
    var buffer = Buffer.from(matches[2], "base64");
    var uploadOptions = {
        container: 'test',
        blob: name,
        text: buffer
    }
    blobServiceClient.createBlockBlobFromText(
      uploadOptions.container,
      uploadOptions.blob,
      uploadOptions.text,
      {
        contentSettings: {
          contentType: type,
        },
      }, 
        function(error, result, response) {
            if (error) {
                res.send(error);
            }
    
            console.log("result", result);
        
            console.log("response", response);
        }
    );  
    

    My result. enter image description here