我正在try 创建一个Azure函数,它可以上载到Azure存储Blob.我正在使用postman 发送请求.在Postman中,我将Body设置为form-data
,将Key设置为file
,然后附加一个测试图像,看看它是否会被上传.但在我的回复中,我得到了一个"没有上传文件".回应.
我不知道是什么导致了这种情况的发生.我甚至添加了额外的日志(log)记录,以便我可以查看Azure日志(log)流,以下是输出:
2024-01-22T17:21:14Z [Information] Request body: ReadableStream { locked: false, state: 'readable', supportsBYOB: false }
2024-01-22T17:21:14Z [Information] Request file: undefined
2024-01-22T17:21:14Z [Information] File uploaded: No file was uploaded
如果您希望查看函数应用程序代码,则该函数的代码如下:
const { BlobServiceClient } = require('@azure/storage-blob');
const { app } = require('@azure/functions');
const multer = require('multer');
const upload = multer();
// Azure Storage connection string
const AZURE_STORAGE_CONNECTION_STRING = process.env['AZURE_STORAGE_CONNECTION_STRING'];
app.http('postToICTDatabaseFiles', {
methods: ['POST'],
authLevel: 'anonymous',
handler: async (request, context) => {
try {
// Log the request body for debugging
context.log("Request body:", request.body);
// Wrap the upload in a new Promise and await it
const file = await new Promise((resolve, reject) => {
upload.single('file')(request, {}, function (err) {
if (err) {
reject(err);
} else {
resolve(request.file);
}
});
});
// Log the file object for debugging
context.log("Request file:", file);
// Print to context.log the file name or if no file was uploaded
context.log(`File uploaded: ${file ? file.originalname : 'No file was uploaded.'}`);
// If file is undefined, return an error
if (!file) {
return {
status: 400,
body: 'No file was uploaded.'
};
}
// Create a BlobServiceClient object which will be used to create a container client
const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);
// Get a reference to a container
const containerClient = blobServiceClient.getContainerClient('files'); // Azure blob storage name
// Create a new block blob and upload the file
const blockBlobClient = containerClient.getBlockBlobClient(file.originalname);
const uploadBlobResponse = await blockBlobClient.upload(file.buffer, file.buffer.length);
context.log(`Upload block blob ${file.originalname} successfully`, uploadBlobResponse.requestId);
// Respond with the result
return {
status: 200,
body: `File uploaded successfully. Blob URL: ${blockBlobClient.url}`
};
} catch (error) {
// Handle errors
// Log or console the error details for debugging
context.log(error.message);
return {
status: 500,
body: error.message
};
}
}
});