从发送到 node.js api 的传入文件上传的 Azure blob 正在创建一个文件,但没有上传我正在发送的文件

Azure blob upload from incoming file sent to node.js api is creating a file, but not uploading the file I am sending in

我需要创建一个函数来接受带有文件附件的传入表单并将其上传到 Azure blob 存储容器。我已经获得了上传到 Azure 的功能。最初我只是得到一个空白文件。但是后来我使用这个 中的信息来重构我的功能。现在我得到一个对象而不是一个空白文件。

目前我的函数如下所示:

    async function uploadFile (req, res) {
      try {
    var formidable = require('formidable');
    var fs = require('fs');
    const storage = require('@azure/storage-blob')
    const { randomBytes } = require('crypto');

    const blobNameUniq = Math.random().toString(36).slice(2) + randomBytes(8).toString('hex') + new Date().getTime();
    const accountname ="MYACCOUNT_HERE";
    const key = "MYKEY_HERE";
    const cerds = new storage.StorageSharedKeyCredential(accountname,key);
    const blobServiceClient = new storage.BlobServiceClient(`https://${accountname}.blob.core.windows.net`,cerds);
    const containerName= blobServiceClient.getContainerClient('dev');
    const containerClient = await blobServiceClient.getContainerClient(containerName.containerName);
    let form = new formidable.IncomingForm();

    form.parse(req, async function (err, fields, files) {
    const file = files.file;
    const blobName = blobNameUniq + files.file;
    const contentType = file.type;
    console.log('content type is: ', contentType)
    const filePath = file.path;//This is where you get the file path.
    console.log('filePath is: ', filePath)
    const blockBlobClient = containerClient.getBlockBlobClient(blobName);
    const uploadBlobResponse = await blockBlobClient.uploadFile(filePath);
        return uploadBlobResponse
  });

 }
     catch (error) {
        console.log(error);
    }
}

我在Azure中看到的(如下图link所示)是文件名末尾的[object Object]和application/octet-stream作为类型。 (我正在测试的文件是 .png。)

感觉问题在于我实际上并没有只将文件发送到 Azure。但是我还没有弄清楚我需要改变什么。

对于它的价值,我有一个函数成功地将我的 Azure blob 存储连接到 return 用于现有 blob 的 SAS。所以我确信我的帐户和帐户密钥是正确的。我也没有从 Azure 收到任何错误消息。通过 console.log 我还可以看到表单正确解析,并且可以看到正确的名称、路径和 mime 类型。

关于我需要更改什么才能使这项工作有什么建议吗?

你得到这个的原因是因为 files.file 是一个对象。

const blobName = blobNameUniq + files.file

请将上面这行代码改为:

const blobName = blobNameUniq + files.file.name

您应该会看到 blob 的正确名称。

谢谢! Gaurav 的更改修复了文件名问题。

我还必须返回并在上传选项中添加以设置内容类型,如下所示。但它现在运行良好。

代码的最后一部分更改为:

form.parse(req, async function (err, fields, files) {
const file = files.file;
const blobName = blobNameUniq + files.file.name;
const contentType = file.type;
console.log('content type is: ', contentType)
const filePath = file.path;//This is where you get the file path.
console.log('filePath is: ', filePath)
const blockBlobClient = containerClient.getBlockBlobClient(blobName);

  // set mimetype as determined from browser with file upload control
const options = { blobHTTPHeaders: { blobContentType: file.type } };
const uploadBlobResponse = await blockBlobClient.uploadFile(filePath, options);
    return uploadBlobResponse