3

I need to store an image to Azure blob storage using nodejs and apollo-server-express.I am using createBlockBlobFromStream for storing but it requires stream length. how can I find the stream length? Is there any better way to store images to azure blob storage using graphql

uploadImageFunc is called by the resolver by passing the args

const fs = require('fs')
const azure = require('azure-storage')
const blobService = azure.createBlobService("connection string")


const uploadImageFunc = async function(args) {
    return args.file.then(file => {
        const {createReadStream, filename, mimetype} = file

        const fileStream = createReadStream()
        
        blobService.createBlockBlobFromStream('container-name',filename,fileStream,"fileStream.length",(error,response) => {
          if(!error){
            console.log(response)
          }
        })

        fileStream.pipe(fs.createWriteStream(__dirname+`/uploadedFiles/${filename}`))

        return file;
        
      });
}

module.exports = uploadImageFunc;

Thanks for responses

albinjose
  • 153
  • 9

1 Answers1

2

Actually, the stream size was present in the content length of the request. req.headers['content-length'] has the content length as a string. convert it into int using parseInt and pass it to the createBlockBlobFromStream function.

const fs = require('fs')
const { v4: uuidv4 } = require('uuid');
const azure = require('azure-storage')
const blobService = azure.createBlobService(process.env.AZURE_STORAGE_CONNECTION_STRING)

const contestEntryModel = require('../models/contestEntryModel')


const uploadImageFunc = async function(args,{req, res}) {
      return args.file.then ( file => {
        const {createReadStream, filename, mimetype} = file

        let streamSize = parseInt(req.headers['content-length'])

        const fileStream = createReadStream()

        const newFilename = uuidv4()
        
      blobService.createBlockBlobFromStream('<container name>',`${args.contestId}/${newFilename}`,fileStream,streamSize,(error,response) => {
        if(!error){
          let entry = {
            url:`<blobstorage url>/${args.contestId}/${newFilename}`,
            participant: req.userId
          }
          contestEntryModel.findOneAndUpdate({contestId: args.contestId},{$push:{entries:entry}},(err, doc) => {
            console.log("updated")
          })
        }
      })


        return true;
        
      });
    
}

module.exports = uploadImageFunc;
albinjose
  • 153
  • 9