azurefile-uploadazure-blob-storageazure-storageblobstorage

Content-Length error in Upload File to Blob Storage


I am trying to upload a file stored in my local system to the Azure blob storage account using Azure Client Library.

Using following code:

const { BlobServiceClient, StorageSharedKeyCredential } = require('@azure/storage-
blob')
const fs = require('fs')

const account = '<account>'
const accountKey = '<SharedKey>'
const sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey)
const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  sharedKeyCredential
)
const containerClient = blobServiceClient.getContainerClient('stream-test-container')
const blockBlobClient = containerClient.getBlockBlobClient('path1/path2/file.xml')
const uploadBlobResponse = blockBlobClient.upload(fs.readFileSync('demo.xml'))
console.log(uploadBlobResponse)

However, I am getting an error that

contentLength cannot be null or undefined.

enter image description here

Can anyone help?


Solution

  • I believe the reason you're getting this error is because you're using incorrect upload method. upload method expects body as HttpRequestBody and contentLength parameters. Since you're not providing the value for contentLength parameter, you're getting this error.

    Instead of upload method, you should use uploadData method. It only expects a data buffer that you will get when you read the file. I just tried your code with uploadData method and it worked well for me.

    So your code would be:

        const { BlobServiceClient, StorageSharedKeyCredential } = require('@azure/storage-blob')
        const fs = require('fs')
        
        const account = '<account>'
        const accountKey = '<SharedKey>'
        const sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey)
        const blobServiceClient = new BlobServiceClient(
          `https://${account}.blob.core.windows.net`,
          sharedKeyCredential
        )
        const containerClient = blobServiceClient.getContainerClient('stream-test-container')
        const blockBlobClient = containerClient.getBlockBlobClient('path1/path2/file.xml')
        const uploadBlobResponse = blockBlobClient.uploadData(fs.readFileSync('demo.xml'))
        console.log(uploadBlobResponse)