-2

我找不到将文件不是作为流(缓冲区,base64)而是作为文件(png,jgeg,jpg)上传到 Azure 存储 Blob 的方法。

我的流代码是

const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  sharedKeyCredential, defaultAzureCredentials
);

createBlob = (blobName,blob)=>{
    try{
      async function main() {
          const containerClient = blobServiceClient.getContainerClient('blue');
          const content = base64_encode(blob.buffer);
          const blockBlobClient = containerClient.getBlockBlobClient(blobName);
          const uploadBlobResponse = await blockBlobClient.upload(content, content.length);
          console.log(`Upload block blob ${blobName} successfully`, uploadBlobResponse.requestId);
          return uploadBlobResponse.requestId;
        }

        main();
  }
  catch(err){
      res.send(err)
  }
}

function base64_encode(file) {
    // read binary data
    //var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return file.toString('base64');
}
4

2 回答 2

2

看来您正在使用@azure/storage-blob并且您的代码灵感来自Create a blob by uploading data to.

有一个功能可以帮助将本地文件直接上传到 Azure Blob Storage,如下图所示uploadFileBlockBlobClient

在此处输入图像描述

这是我的示例代码。

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

// Enter your storage account name and shared key
const account = "<your account name>";
const accountKey = "<your account key>";

// Use StorageSharedKeyCredential with storage account and account key
// StorageSharedKeyCredential is only avaiable in Node.js runtime, not in browsers
const sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey);
const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  sharedKeyCredential
);

var containerName = '<your container name>';
var blobName = '<your blob name>';

const containerClient = blobServiceClient.getContainerClient(containerName);
const blockBlobClient = containerClient.getBlockBlobClient(blobName);

var filePath = '<your local file path>';
blockBlobClient.uploadFile(filePath);
于 2020-01-30T19:31:01.867 回答
1

您可以在选项中指定内容类型

  await blockBlobClient.uploadStream(stream, bufferSize, maxConcurrency, {
    blobHTTPHeaders: {
      blobContentType: "image/jpeg"
    }
  })

于 2020-03-31T18:12:14.247 回答