1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
const express = require('express') const app = express() const port = 6000 const bodyParser = require('body-parser'); const multer = require('multer') const inMemoryStorage = multer.memoryStorage(); const singleFileUpload = multer({ storage: inMemoryStorage }); const azureStorage = require('azure-storage'); const getStream = require('into-stream'); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })); // parse application/json app.use(bodyParser.json()); const azureStorageConfig = { accountName: "", accountKey: "", blobURL: "", containerName: "" }; uploadFileToBlob = async (directoryPath, file) => { return new Promise((resolve, reject) => { const blobName = getBlobName(file.originalname); const stream = getStream(file.buffer); const streamLength = file.buffer.length; const blobService = azureStorage.createBlobService(azureStorageConfig.accountName, azureStorageConfig.accountKey); blobService.createBlockBlobFromStream(azureStorageConfig.containerName, `${directoryPath}/${blobName}`, stream, streamLength, err => { if (err) { reject(err); } else { resolve({ filename: blobName, originalname: file.originalname, size: streamLength, path: `${azureStorageConfig.containerName}/${directoryPath}/${blobName}`, url: `${azureStorageConfig.blobURL}${azureStorageConfig.containerName}/${directoryPath}/${blobName}` }); } }); }); }; const getBlobName = originalName => { const identifier = Math.random().toString().replace(/0\./, ''); // remove "0." from start of string return `${identifier}-${originalName}`; }; const imageUpload = async(req, res, next) => { try { const image = await uploadFileToBlob('images', req.file); // images is a directory in the Azure container return res.json(image); } catch (error) { next(error); } } app.post('/upload/image', singleFileUpload.single('image'), imageUpload) app.listen(port, () => console.log(`Example app listening on port ${port}!`)) |

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.
Thanks!
what should be the blobURL and directoryPath?