将文件上传到 Blob 存储时出现内容长度错误

Content-Length error in Upload File to Blob Storage

我正在尝试使用 Azure 客户端库将本地系统中存储的文件上传到 Azure blob 存储帐户。

使用以下代码:

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)

但是,我收到一个错误

contentLength cannot be null or undefined.

有人能帮忙吗?

我认为您收到此错误的原因是您使用的上传方法不正确。 upload 方法需要正文作为 HttpRequestBodycontentLength 参数。由于您没有为 contentLength 参数提供值,因此您会收到此错误。

您应该使用 uploadData 方法,而不是 upload 方法。它只需要一个数据缓冲区,您在读取文件时将获得该缓冲区。我刚刚用 uploadData 方法尝试了你的代码,它对我来说效果很好。

因此您的代码将是:

    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)