require("dotenv").config(); const { BlobServiceClient } = require("@azure/storage-blob"); // const { v1: uuidv1 } = require("uuid"); async function azureblob(idnow, imageto, imageb64) { const AZURE_STORAGE_CONNECTION_STRING = process.env.AZURE_BLOB_ACCESS; if (!AZURE_STORAGE_CONNECTION_STRING) { throw Error("Azure Storage Connection string not found"); } // Create the BlobServiceClient object which will be used to create a container client const blobServiceClient = BlobServiceClient.fromConnectionString( AZURE_STORAGE_CONNECTION_STRING ); const containerName = imageto; const blobName = idnow + ".jpeg"; // To Create New container // console.log(containerClient); // const createContainerResponse = await containerClient.create(); // console.log( // "Container was created successfully. requestId: ", // createContainerResponse.requestId // ); var FormData = require("form-data"); var fs = require("fs"); if (imageto && idnow) { try { const containerClient = blobServiceClient.getContainerClient(containerName); // It convert to base64 which like i will send // const ifileSelected = fs.readFileSync( // "../assets/mess_default_image.jpeg", // { encoding: "base64" } // ); let ifileSelected = imageb64; // Converting that img to buffer and using it let bufferObj = Buffer.from(ifileSelected, "base64"); let finalbuffer = Buffer.from(bufferObj, "utf8"); // console.log("final trial", finalbuffer); const blockBlobClient = containerClient.getBlockBlobClient(blobName); // console.log("\nUploading to Azure storage as blob:\n\t", blobName); const blobOptions = { blobHTTPHeaders: { blobContentType: "image/jpeg" }, }; const uploadBlobResponse = await blockBlobClient.upload( finalbuffer, finalbuffer.length, blobOptions ); console.log( "Blob of ", idnow, " uploaded successfully. \nrequestId: ", uploadBlobResponse.requestId, " at ", imageto ); } catch (err) { console.log("There is some error:", err); } } else { console.log("Image Not Uploaded"); } // console.log("\nListing blobs...") // List the blob(s) in the container. // for await (const blob of containerClient.listBlobsFlat()) { // console.log("\t", blob.name); // } // Delete container // console.log("\nDeleting container..."); // const deleteContainerResponse = await containerClient.delete(); // console.log( // "Container was deleted successfully. requestId: ", // deleteContainerResponse.requestId // ); } // It auto run when called // azureblob() // .then(() => console.log("Done")) // .catch((ex) => console.log("I'm exception: ", ex.message)); module.exports = { azureblob };