我想上传通过 Base64 表单从网络应用程序和移动应用程序发送的用户的个人资料图片。
在 POST
请求中,他们需要在正文上发送一个 JSON
,如下所示。
{
"name":"profile-pic-123.jpg",
"file":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQTEhIUEhIUFBUV…K9rk8hCAEkjFMUYiEAI+nHIpsQh0AkisDYRTOiCAbWVtgCtI6IlkHh7LDTQXLH0EIQBj//2Q==" // the base64 image
}
现在在服务器端使用 Node
和 Express
,我使用了这个名为 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/