首页 > 解决方案 > 使用 Azure 函数从 Azure Blob 存储下载文件会返回不同的文件大小

问题描述

我们正在尝试使用 Azure 函数为托管在 Azure blob 存储中的文件提供服务。获取它们时,我们收到以下错误:

Uncaught (in promise) Error: Length in header does not match actual data length: X != Y

我对这类事情不是很精通,但我们的开发人员正在绞尽脑汁,我也很空虚。

我们认为是罪魁祸首的 Azure 函数中的代码片段是:

const streamToBuffer = async (readableStream) => {
  return new Promise((resolve, reject) => {
    const chunks = [];
    readableStream.on('data', (data) => {
      chunks.push(data instanceof Buffer ? data : Buffer.from(data));
    });
    readableStream.on('end', () => {
      resolve(Buffer.concat(chunks));
    });
    readableStream.on('error', reject);
  });
};

编辑:

    const blobClient = containerClient.getBlobClient(path);

    if (await blobClient.exists()) {
      const downloadBlockBlobResponse = await blobClient.download();

      const content = (
        await streamToBuffer(downloadBlockBlobResponse.readableStreamBody)
      ).toString();

编辑2:

跟踪中的错误:

Uncaught (in promise) Error: Can not parse environment file at god3.js:16
Uncaught (in promise) Error: Length in header does not match actual data length: X != Y
Error while trying to use the following icon from the Manifest: $url (Download error or resource isn't a valid image)

我们仅在通过 Azure 函数提供数据时遇到此问题。我们已经尝试将逻辑托管在不同的平台上,并且在拉取文件时它可以工作。

函数的附加部分:

  const containerClient = blobServiceClient.getContainerClient('site');

    const blobClient = containerClient.getBlobClient(path);

    if (await blobClient.exists()) {
      const downloadBlockBlobResponse = await blobClient.download();

      const content = (
        await streamToBuffer(downloadBlockBlobResponse.readableStreamBody)
      ).toString();

      context.res = {
        headers: {
          'Content-Type': downloadBlockBlobResponse.contentType,
        },
        body: content,
      };
    } else {
      context.res = {
        status: 404,
      };
    }
  } else {
    context.res = {
      status: 401,
      headers: { 'WWW-Authenticate': 'Basic realm=Access to the staging site' },
      body: { success: false },
    };
  }
};

任何指针将不胜感激。

谢谢

标签: javascriptazureazure-functionsazure-blob-storage

解决方案


我们发现了问题。

我们正在对二进制文件进行字符串化,BabylonJS 对此并不欣赏。

解决方案是在函数中添加文件类型检查。

      const content = await streamToBuffer(
        downloadBlockBlobResponse.readableStreamBody,
      );
      const fileType = path.split('.').slice(-1)[0];
      context.res = {
        headers: {
          'Content-Type': downloadBlockBlobResponse.contentType,
        },
        body: textPlainType.has(fileType) ? content : content.toString(),
      };

推荐阅读