Nodejs 使用 .createBlockBlobFromLocalFile() 将 base64 图像上传到 azure blob 存储

CEN*_*EDE 3 azure azure-storage node.js azure-blob-storage

我想上传通过 Base64 表单从网络应用程序和移动应用程序发送的用户的个人资料图片。

\n\n

根据POST请求,他们需要JSON在正文上发送一个看起来像这样的内容。

\n\n
{\n    "name":"profile-pic-123.jpg",\n    "file":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQTEhIUEhIUFBUV\xe2\x80\xa6K9rk8hCAEkjFMUYiEAI+nHIpsQh0AkisDYRTOiCAbWVtgCtI6IlkHh7LDTQXLH0EIQBj//2Q==" // the base64 image\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在在服务器端使用NodeExpress,我使用了这个 npm 模块,azure-storage它提供了一种使用 Web 服务将文件上传到 azure blob 存储的好方法。

\n\n

但有一点我无法理解。这是我的控制器的部分代码。我成功创建了所有必要的连接和密钥以及其他创建工作的内容blobService

\n\n
controllers.upload = function(req, res, next){\n\n    // ...\n    // generated some sastoken up here\n    // etc.\n    // ...\n\n    var uploadOptions = {\n        container: \'mycontainer\',\n        blob: req.body.name, // im not sure about this\n        path: req.body.file // im not sure about this either\n    }\n\n    sharedBlobService.createBlockBlobFromLocalFile(uploadOptions.container, uploadOptions.blob, uploadOptions.path, function(error, result, response) {\n        if (error) {\n            res.send(error);\n        }\n        console.log("result", result);\n        console.log("response", response);\n    });\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我收到此错误:

\n\n
{\n    "errno": 34,\n    "code": "ENOENT",\n    "path": "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAIAAAB..."\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Ahm*_*rif 5

如果您使用 javascript sdk v12 您可以使用此示例代码。就是这么简单。我在一个函数中实现了这个,当我需要它来触发 HTTP 事件时,它工作得很好。

索引.js

 const file = await require('./file')();
    uploadOptions = {
        container: 'mycontainer',
        blob: req.body.name, 
        text: req.body.file 
    }

      const fileUploader = await file(uploadOptions.text, uploadOptions.blob, 

uploadOptions.container);
Run Code Online (Sandbox Code Playgroud)

您可以为您的逻辑使用单独的模块,并从上面的 index.js 调用它

文件.js

    const { BlobServiceClient } = require("@azure/storage-blob");
    const blobServiceClient = BlobServiceClient.fromConnectionString(process.env.AZURE_STORAGE_CONNECTION_STRING);
const Promise = require('bluebird');

    module.exports = Promise.method(async function() {

        return async function (data, fileName, container) {
            const containerClient = await blobServiceClient.getContainerClient(container);
            const blockBlobClient = containerClient.getBlockBlobClient(fileName);
            const matches = data.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
            const buffer = new Buffer(matches[2], 'base64');

            return await blockBlobClient.upload(buffer, buffer.byteLength );
        };
    });
Run Code Online (Sandbox Code Playgroud)