【发布时间】:2021-07-02 14:49:47
【问题描述】:
我需要创建一个函数来接受带有文件附件的传入表单并将其上传到 Azure blob 存储容器。我已经获得了上传到 Azure 的功能。最初我只是得到一个空白文件。但后来我使用了stackoverflow question 中的信息来重组我的功能。现在我得到一个对象而不是一个空白文件。
目前我的函数如下所示:
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 中看到的(如下链接所示)是文件名末尾的 [object Object] 和 application/octet-stream 作为类型。 (我正在测试的文件是 .png。)
感觉问题在于我实际上并没有将文件发送到 Azure。但我无法弄清楚我需要改变什么。
对于它的价值,我有一个函数成功连接到我的 Azure blob 存储以返回现有 blob 的 SAS。所以我确信我的帐户和帐户密钥是正确的。我也没有从 Azure 收到任何错误消息。通过 console.log,我还可以看到表单解析正确,并且可以看到正确的名称、路径和 mime 类型。
对我需要更改哪些内容以使其正常工作有什么建议吗?
【问题讨论】:
标签: node.js azure file-upload