繁体   English   中英

如何修复Node.js azure blob以上传和下载azure blob存储中的文件

[英]How to fix Node.js azure blob to upload and download files in azure blob storage

我有一个 node.js 应用程序,我想使用 Azure Blob 存储作为我通过 Node.js 上传文件和下载文件的地方

我已按照以下说明操作: https : //github.com/Azure-Samples/storage-blob-upload-from-webapp-node/tree/master/

我已经创建了我的 blob 存储帐户,但是现在当我运行我的应用程序时,我收到以下错误:

 There was an error contacting the blob storage container.

 StorageError: The specified container does not exist.

 \node_modules\azure-storage\lib\common\services\storageserviceclient.js:1191:23)

node_modules\azure-storage\lib\common\services\storageserviceclient.js:738:50

node_modules\azure-storage\lib\common\services\storageserviceclient.js:311:37)

node_modules\request\request.js:188:22

node_modules\request\request.js:1171:10

根据我的测试,我们可以使用以下代码进行上传下载 1.安装sdk

my package.json

"dependencies": {
    "@azure/abort-controller": "^1.0.1",
    "@azure/storage-blob": "^12.0.2",    
    "fs": "0.0.1-security",
    "stream": "0.0.2"
  }
  1. 代码
const accountname ="blobstorage0516";
    const key = "your account key";
    const cerds = new storage.StorageSharedKeyCredential(accountname,key);
    const containerName="test";
    const pipeline = storage.newPipeline(cerds, {
      retryOptions: { maxTries: 4 }, // Retry options
      userAgentOptions: { userAgentPrefix: "AdvancedSample V1.0.0" }, // Customized telemetry string
      keepAliveOptions: {
        // Keep alive is enabled by default, disable keep alive by setting false
        enable: false
      }
    });
    const blobServiceClient =new storage.BlobServiceClient( `https://${accountname}.blob.core.windows.net`,pipeline)
    var containerClient =blobServiceClient.getContainerClient(containerName)
    if(!containerClient.exists()){
       console.log("the container does not exit")
       await containerClient.create()

    }
    const blobNmae="test.jpg";
    const localFilePath="D:\\download\\test.jpg";
    const blockBlobClient =containerClient.getBlockBlobClient(blobNmae)
    // upload
    await blockBlobClient.uploadStream(fs.createReadStream(localFilePath), 4 * 1024 * 1024, 20, {
    abortSignal: AbortController.timeout(30 * 60 * 1000)})
    // download
    const downloadBlockBlobResponse = await blockBlobClient.download(0);
    const  datastream =  new stream.PassThrough();
    const  readableStream = downloadBlockBlobResponse.readableStreamBody
    readableStream.on("data", data => {
      datastream.push(data);

    });
    readableStream.on("end" , () => {
      fs.writeFileSync('D:\\test1.jpg', datastream.read())
      console.log("download successfully")
      datastream.destroy();

  });
  readableStream.on("error" , (error) => {

    datastream.destroy();
    throw error;

  });

更多详细信息,请参阅文档示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM