且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Node和graphql将上传文件流式传输到Azure blob存储

更新时间:2023-02-09 08:55:16

实际上,流大小出现在请求的内容长度中. req.headers ['content-length'] 的内容长度为字符串.使用parseInt将其转换为int并将其传递给 createBlockBlobFromStream 函数.

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;