【问题标题】:How to upload image to Azure Blob storage如何将图像上传到 Azure Blob 存储
【发布时间】:2020-01-25 09:44:25
【问题描述】:

我阅读并发现上传图片的最佳方式是使用 Blob 存储。我想将它与 node.js 一起使用。如何使用 node.js 代码将图像上传到 blob?

【问题讨论】:

  • 我看到它与本地文件一起工作。如果我希望该用户可以将图像作为客户端上传并将该图像发送到服务器(node.js)。然后服务器将其上传到我需要在服务器中使用的blob?
  • 假设您可以将图像上传到流,然后使用createPageBlobFromStream

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


【解决方案1】:

如果你想在 nodejs 中使用 Blob,有发布包来实现它。它是一个 Node.js 包和一个与浏览器兼容的 JavaScript 客户端库,可以轻松使用和管理 Microsoft Azure 存储服务。

更多细节可以参考这个github页面:Azure Storage SDK for Node.js。您可以使用createBlockBlobFromLocalFile 直接将本地文件上传到 blob。

您还可以将文件上传到流中以创建 blob。如果你想要一些示例,你可以参考下面的代码。

var azure = require('azure-storage');
var blobService = azure.createBlobService("connection string");
blobService.createBlockBlobFromLocalFile('mycontainer', 'taskblob', 'task1-upload.txt', function(error, result, response) {
  if (!error) {
    // file uploaded
  }
});

除此之外,您可以参考Azure Blob nodejs官方教程:using the client library for Node.js

【讨论】:

  • @עידן עובדיה,你能解决吗?如果这可以帮助您,您可以接受它作为答案。如果您仍有问题,请随时告诉我。
【解决方案2】:

您可以使用以下列出的 SDK

https://github.com/Azure/azure-storage-node#microsoft-azure-storage-sdk-for-nodejs-and-javascript-for-browsers

如果您不修改现有代码并从头开始编写更好,您可以使用第一个(Storage SDK v10 for javascript)。您可以参考下面的代码:

const {
    Aborter, BlobURL,
    BlockBlobURL, ContainerURL,
    ServiceURL,
    StorageURL,
    SharedKeyCredential,
    generateBlobSASQueryParameters,
    uploadStreamToBlockBlob,
    BlobSASPermissions,
    SASProtocol,
    AnonymousCredential,
} = require("@azure/storage-blob");

const STORAGE_ACCOUNT_NAME = process.env.STORAGE_ACCOUNT;
const ACCOUNT_ACCESS_KEY = process.env.STORAGE_KEY;
const AS = {};    // Azure Storage
console.log(STORAGE_ACCOUNT_NAME);
/*
const ONE_MEGABYTE = 1024 * 1024;
const FOUR_MEGABYTES = 4 * ONE_MEGABYTE;
const ONE_MINUTE = 60 * 1000;
By default, credential is always the last element of pipeline factories
const factories = serviceURL.pipeline.factories;
const sharedKeyCredential = factories[factories.length - 1];
*/

AS.getServiceUrl = () => {
    const credentials = new SharedKeyCredential(STORAGE_ACCOUNT_NAME, ACCOUNT_ACCESS_KEY);
    const pipeline = StorageURL.newPipeline(credentials);
    const serviceURL = new ServiceURL(`https://${STORAGE_ACCOUNT_NAME}.blob.core.windows.net`, pipeline);
    return serviceURL;
}

AS.createBlockBlobSASToken = (blobName, containerName, options) => {
    const now = new Date();
    now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
    const tmr = new Date();
    tmr.setDate(tmr.getDate() + 1);
    const credentials = new SharedKeyCredential(STORAGE_ACCOUNT_NAME, ACCOUNT_ACCESS_KEY);
    const blobSAS = generateBlobSASQueryParameters(
        {
            blobName,
            containerName,
            expiryTime: tmr,
            permissions: BlobSASPermissions.parse("racwd").toString(),
            protocol: SASProtocol.HTTPSandHTTP,
            startTime: now,
        },
        credentials
    );
    //const sasURL = `${blobURL.url}?${blobSAS}`;
    return blobSAS
}


AS.createContainerSASToken = (containerName, options) => {
    const now = new Date();
    now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
    const tmr = new Date();
    tmr.setDate(tmr.getDate() + 1);
    const credentials = new SharedKeyCredential(STORAGE_ACCOUNT_NAME, ACCOUNT_ACCESS_KEY);
    const containerSAS = generateBlobSASQueryParameters(
        {
            containerName,
            expiryTime: tmr,
            permissions: ContainerSASPermissions.parse("racwdl").toString(),
            protocol: SASProtocol.HTTPSandHTTP,
            startTime: now,
            version: "2016-05-31"
        },
        credentials
    );
    // const sasURL = `${containerURL.url}?${containerSAS}`;
    return containerSAS;
}

AS.createBlockBlobSASURL = (blobName, containerName) => {
    let blockBlobURL = getBlockBlobUrl(blobName, containerName);
    let blobSAS = createBlockBlobSASToken(blobName, containerName);
    const sasURL = `${blockBlobURL.url}?${blobSAS}`;
    return sasURL;
}

AS.createContainer = (containerName) => {
    const serviceURL = getServiceUrl();
    const containerURL = ContainerURL.fromServiceURL(serviceURL, containerName);
    return containerURL.create(Aborter.none);
}

AS.getBlockBlobUrl = (blobName, containerName) => {
    const serviceURL = getServiceUrl();
    const containerURL = ContainerURL.fromServiceURL(serviceURL, containerName);
    const blockBlobURL = BlockBlobURL.fromContainerURL(containerURL, blobName);
    return blockBlobURL;
}

AS.uploadToBlockBlobFromStream = (blobName, containerName, readableStream, fileSizeInBytes) => {
    const blockBlobURL = getBlockBlobUrl(blobName, containerName);
    return uploadStreamToBlockBlob(Aborter.none,
        readableStream,
        blockBlobURL,
        256 * 1024,
        2,
        {
            progress: function (ev) {
                console.log((ev.loadedBytes / fileSizeInBytes) * 100);
            }
        }
    )
}

// const uploadFileFromBuffer = (blobName, containerName,buffer, fileSizeInBytes) =>{


// }

AS.uploadBlockBlobWithSAS = (blobName, containerName, readableStream, fileSizeInBytes) => {
    const blockBlobSasUrl = createBlockBlobSASURL(blobName, containerName);
    let blockBlobURL = new BlockBlobURL(blockBlobSasUrl, StorageURL.newPipeline(new AnonymousCredential()))
    return uploadStreamToBlockBlob(Aborter.none,
        readableStream,
        blockBlobURL,
        4 * 1024 * 1024,
        2,
        {
            progress: function (ev) {
                console.log((ev.loadedBytes / fileSizeInBytes) * 100);
            }
        }
    )
}

AS.deleteBlockBlob = (blobName, containerName) => {
    const blockBlobURL = getBlockBlobUrl(blobName, containerName);
    return blockBlobURL.delete(Aborter.none)

}

AS.downloadBlob = async (blobName, containerName) => {
    const blockBlobURL =  await getBlockBlobUrl(blobName, containerName);
    const downloadStream = await blockBlobURL.download(aborter, 0);
    return downloadStream;
}

module.exports = AS;

【讨论】:

    猜你喜欢
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 2021-01-16
    • 2020-01-09
    • 2020-06-07
    • 2014-07-22
    • 2020-02-23
    相关资源
    最近更新 更多