gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:25:59 37 4
gpt4 key购买 nike

我需要创建一个函数来接受带有文件附件的传入表单并将其上传到 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 Storage Screen Shot

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

无论如何,我有一个函数成功连接到我的 Azure Blob 存储,以返回现有 Blob 的 SAS。所以我确信我的帐户和帐户 key 是正确的。我也没有从 Azure 收到任何错误消息。通过 console.log,我还可以看到表单已正确解析,并且可以看到正确的名称、路径和 MIME 类型。

对于我需要进行哪些更改才能使其正常工作,您有什么建议吗?

最佳答案

谢谢! 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

关于node.js - Azure blob 从发送到 node.js api 的传入文件上传正在创建一个文件,但没有上传我要发送的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66975094/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com