我正在try 创建一个Azure函数,它可以上载到Azure存储Blob.我正在使用postman 发送请求.在Postman中,我将Body设置为form-data,将Key设置为file,然后附加一个测试图像,看看它是否会被上传.但在我的回复中,我得到了一个"没有上传文件".回应.

postman response

我不知道是什么导致了这种情况的发生.我甚至添加了额外的日志(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
      };
    }
  }
});

推荐答案

我已经创建了http触发器函数与运行时堆栈的Java脚本.

我已经try 使用以下代码将BLOB上传到Azure存储容器中.

Function code:

const { BlobServiceClient, StorageSharedKeyCredential } = require('@azure/storage-blob');
const multipart = require('parse-multipart');

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    if (req.method === 'POST' && req.headers['content-type'] && req.headers['content-type'].startsWith('multipart/form-data')) {
        // Encode body to base64 string
        const bodyBuffer = Buffer.from(req.body);
        // Get boundary for multipart data
        const boundary = multipart.getBoundary(req.headers['content-type']);
        // Parse the body
        const parts = multipart.Parse(bodyBuffer, boundary);

        if (parts.length > 0) {
            const storageAccountName = 'pavanstoragehello';
            const storageAccountKey = 'your-storage account access key';
            const containerName = 'pavan';

            const sharedKeyCredential = new StorageSharedKeyCredential(storageAccountName, storageAccountKey);
            const blobServiceClient = new BlobServiceClient(`https://${storageAccountName}.blob.core.windows.net`, sharedKeyCredential);
            const containerClient = blobServiceClient.getContainerClient(containerName);

            const blobName = parts[0].filename;
            const blockBlobClient = containerClient.getBlockBlobClient(blobName);

            const uploadOptions = { blobHTTPHeaders: { blobContentType: parts[0].type } };

            // Upload the file to Azure Storage
            await blockBlobClient.upload(parts[0].data, parts[0].data.length, uploadOptions);

            context.res = {
                body: { message: 'File uploaded successfully.' },
                headers: { 'Content-Type': 'application/json' },
                status: 200
            };
        } else {
            context.res = {
                body: { message: 'No file data found in the request.' },
                headers: { 'Content-Type': 'application/json' },
                status: 400
            };
        }
    } else {
        context.res = {
            body: { message: 'Invalid request. Please use a POST request with "multipart/form-data" content type.' },
            headers: { 'Content-Type': 'application/json' },
            status: 400
        };
    }

    context.done();
};

function.json:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}

通过使用POST Endpoint,我可以通过表单数据将文件发送到Azure BLOB存储.

enter image description here

我可以在Azure BLOB存储容器中看到上传的文件.请查看以下内容:

Output:

enter image description here

Node.js相关问答推荐

Spotify Auth访问令牌给出错误代码400

错误:找不到模块';/var/apps/前端/bash';

MongoDB-$Lookup未获得适当的结果

SvelteKit应用程序立即退出,没有错误

表达 js 错误处理程序在第一个之后被忽略

如何在 JavaScript 中显示多维数组中使用的一维数组的变量名?

如何在带有 JS 的 Nodejs 中使用没有 Async 方法的 Await

当其中一个端点不工作时,如何使用 axios.all() 调用多个 API?

npm install 在 Mac 上的 Node-gyp 构建错误

Express.js - 监听请求中止

tsc:当我上传 React+next js 和 node 项目时,在 heroku 找不到

在 gatsby 中安装软件包时不推荐使用的错误

Firestore promise 在退货前等待产品详细信息

为什么我在生产环境中 deproy Next.js 示例项目时 CSS 不起作用?

Socket IOFlutter 未连接

如何防止 node.js 中的内存泄漏?

使用加密模块的流功能获取文件的哈希(即:没有 hash.update 和 hash.digest)

Bootstrap 中的 Grunt 依赖冲突

npm WARN 不推荐使用 graceful-fs@3.0.8:graceful-fs 版本 3

使用 gzip/deflate 压缩的简单 HTTP 请求