Upload Image to azure blob from a URL using azure functions in Nodejs

Viewed 301

I have a requirement where the user wants to upload an image from a source URL let's say "https://homepages.cae.wisc.edu/~ece533/images/airplane.png" using Azure functions. Right now what I am trying to do is I am calling fetch method and pass the image URL and converting that into the blob but somehow that doesn't seem to be working. Below is the code. Is there any better way to achieve this

const { BlobServiceClient } = require("@azure/storage-blob");

const fetch = require("node-fetch");

const multipart = require("parse-multipart");

const AZURE_STORAGE_CONNECTION_STRING = process.env["AZURE_STORAGE_CONNECTION_STRING"];


module.exports = async function (context, req) {
    context.log("JavaScript HTTP trigger function processed a request.");

    const name =
        req.query.name ||
        (req.body &&
            req.body.secure_url);
    const responseMessage = name
         ? "Hello, " + name + ". This HTTP triggered function executed successfully."
         : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";
    // context.log("requested body: ", req.body);

   

    var images = "\""+ req.body.secure_url.toString() +"\"";
  
    context.log("Image URL : ", images);


    var bodyBuffer = Buffer.from(JSON.stringify(req.body));
    let header = req.headers["content-type"]
    let boundary  = header.split(" ")[1]
        boundary = header.split("=")[1]

    // var boundary = multipart.getBoundary(req.headers['content-type']);

    var parts = multipart.Parse(req.body, header);

  
    var requestOptions = {
        method: 'GET'
    };

   fetch(images, requestOptions)
    .then((response) => {
        context.log("Response Blob : ",response.blob())
        response.blob()
    }) // Gets the response and returns it as a blob
    .then((blob) => { main(blob)
    }).catch(error => console.log('error', error));

async function main(blob) {
  const blobServiceClient = await BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);

        const container = "sepik01-rdp-media-assets-migration";
        const containerClient = await blobServiceClient.getContainerClient(container);
        const blobName = images.toString().replace(/^.*[\\\/]/, "");

        context.log("File Name: ", blobName);
        const blockBlobClient = containerClient.getBlockBlobClient(blobName);
    
        // const uploadBlobResponse = await blockBlobClient.upload(parts[0].secure_url, parts[0].length);
        const uploadBlobResponse = await blockBlobClient.upload(blob, blob.length);
        context.res = { body : responseMessage };

        context.done();
}








 
};

1 Answers

when we use package node-fetch to send HTTP request, the response.body will return as Readable stream. Then we can use the stream to upload data to azure blob.

For example

const fetch = require("node-fetch");
const { BlobServiceClient } = require("@azure/storage-blob");
const mime = require("mime");

const AZURE_STORAGE_CONNECTION_STRING =""

module.exports = async function (context, req) {
  const images = "https://homepages.cae.wisc.edu/~ece533/images/airplane.png";

  const requestOptions = {
    method: "GET",
  };

  const response = await fetch(images, requestOptions);

  if (!response.ok)
    throw new Error(`unexpected response ${response.statusText}`);
  const blobName = images.toString().replace(/^.*[\\\/]/, "");
  const blobServiceClient = await BlobServiceClient.fromConnectionString(
    AZURE_STORAGE_CONNECTION_STRING
  );

  const containerClient = await blobServiceClient.getContainerClient("image");
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);
  const uploadBlobResponse = await blockBlobClient.uploadStream(
    response.body,
    4 * 1024 * 1024,
    20,
    {
      blobHTTPHeaders: {
        blobContentType: mime.getType(blobName),
      },
    }
  );
  context.res = { body: uploadBlobResponse._response.status };
};

enter image description here

Related