I am uploading a stream to azure blob container and it uploads to the container just fine, but I don't know how to get the url that the image created so I can return it to my initial call and render it in my UI.
I can get the request ID back, would that allow me to do a request from there and get the image URL, do I need another request and if so how would I compose that?
Thanks ahead of time
I have the following
import formidable from 'formidable';
let streamifier = require('streamifier');
const fs = require('fs');
const os = require('os');
const {
BlobServiceClient,
StorageSharedKeyCredential,
newPipeline
} = require('@azure/storage-blob');
const containerName1 = 'images';
const ONE_MEGABYTE = 1024 * 1024;
const uploadOptions = { bufferSize: 4 * ONE_MEGABYTE, maxBuffers: 20 };
const sharedKeyCredential = new StorageSharedKeyCredential(
process.env.AZURE_STORAGE_ACCOUNT_NAME,
process.env.AZURE_STORAGE_ACCOUNT_ACCESS_KEY
);
const pipeline = newPipeline(sharedKeyCredential);
const blobServiceClient = new BlobServiceClient(
`https://${process.env.AZURE_STORAGE_ACCOUNT_NAME}.blob.core.windows.net`,
pipeline
);
// first we need to disable the default body parser
export const config = {
api: {
bodyParser: false
}
};
export default async function image(req, res) {
try {
const form = new formidable.IncomingForm();
form.uploadDir = os.tmpdir();
form.keepExtensions = true;
form.parse(req, async (err, fields, files) => {
var oldPath = files.image.path;
var rawData = fs.readFileSync(oldPath);
const buffer = rawData;
const stream = streamifier.createReadStream(buffer);
const containerClient = blobServiceClient.getContainerClient(
containerName1
);
const blockBlobClient = containerClient.getBlockBlobClient(
files.image.name
);
const result = await blockBlobClient.uploadStream(
stream,
uploadOptions.bufferSize,
uploadOptions.maxBuffers,
{ blobHTTPHeaders: { blobContentType: 'image/jpeg' } }
);
console.log('result >>>>', result);
// HERE I AM TRYING TO GET THE IMAGE URL, BUT IT JUST GIVES ME A OBJECT WITH REQUEST
// ID AND SUCH
res.status(200).send({ message: 'File Uploaded' });
});
} catch (error) {
console.error(error);
res.status(error.requestResult.statusCode).send(error.message);
}
}
If all you're interested in is getting the blob URL, you don't have to do anything special. BlockBlobClient
has a property called url
which will give you the URL of the blob.
Your code could be as simple as:
res.status(200).send({ message: 'File Uploaded', url: blockBlobClient.url });