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

标签 node.js azure azure-storage azure-blob-storage

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

POST 请求中,他们需要在正文上发送一个 JSON,如下所示。

{
    "name":"profile-pic-123.jpg",
    "file":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQTEhIUEhIUFBUV…K9rk8hCAEkjFMUYiEAI+nHIpsQh0AkisDYRTOiCAbWVtgCtI6IlkHh7LDTQXLH0EIQBj//2Q==" // the base64 image
}

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

但是有一些我无法理解的事情。这是我的 Controller 的部分代码。我成功创建了所有必要的连接和 key 以及其他创建工作 blobService 的内容:

controllers.upload = function(req, res, next){

    // ...
    // generated some sastoken up here
    // etc.
    // ...

    var uploadOptions = {
        container: 'mycontainer',
        blob: req.body.name, // im not sure about this
        path: req.body.file // im not sure about this either
    }

    sharedBlobService.createBlockBlobFromLocalFile(uploadOptions.container, uploadOptions.blob, uploadOptions.path, function(error, result, response) {
        if (error) {
            res.send(error);
        }
        console.log("result", result);
        console.log("response", response);
    });
}

我收到此错误:

{
    "errno": 34,
    "code": "ENOENT",
    "path": "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAIAAAB..."
}

最佳答案

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

index.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);

您可以为您的逻辑使用单独的模块,并从上面的 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 );
        };
    });

关于node.js - Nodejs 使用 .createBlockBlobFromLocalFile() 将 base64 图像上传到 azure blob 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36079353/

相关文章:

node.js - 在 MongoDB 驱动程序中监听重新连接事件

php - 从 Azure 网站中的 Blob 存储获取损坏的图像

azure - 微软Azure Java SDK : snapshot copy

javascript - Node.js 异步 waterfall ()回调已被调用

node.js - 确定 npm 将为给定版本范围选择哪个版本的包

node.js - Nodejs --debug-brk 极慢

c# - 并行查询 Azure 存储

sql-server - 如何查看 Sql Azure 上的关系?

Azure AD 访问 token 不包含组声明

azure - Azure存储表查询实体真的有数量限制吗?