LoginSignup
0
0

Node.jsでAzureBLOBStorage内へリソースのアップロード、ダウンロードする

Last updated at Posted at 2024-01-31

Node.jsからazure blob storage内のリソースをアップロード、ダウンロードするためのコードを紹介します。

まずは、Azure SDKをインストールします。

npm install @azure/storage-blob

次に、指定したファイルをblob storageにアップロードします。

upload
// Azure Storage Blob SDKをインポート
const { BlobServiceClient } = require('@azure/storage-blob');

async function uploadBlob(containerName, blobName, content) {
    // 環境変数から接続文字列を使ってBlobServiceClientインスタンスを作成
    const blobServiceClient = BlobServiceClient.fromConnectionString(process.env.AZURE_STORAGE_CONNECTION_STRING);
    
    // 指定されたコンテナ名からContainerClientインスタンスを取得
    const containerClient = blobServiceClient.getContainerClient(containerName);
    
    // 指定されたブロブ名でBlockBlobClientインスタンスを取得
    const blockBlobClient = containerClient.getBlockBlobClient(blobName);

    // ブロブにコンテンツをアップロード
    // 第二引数にはアップロードするコンテンツのサイズを指定
    const uploadBlobResponse = await blockBlobClient.upload(content, content.length);
    
    // アップロードが成功したことをコンソールに表示
    console.log('Upload Success');
}

// 関数を呼び出し、'sample'コンテナに'text'という名前で'Hello World'をアップロード
uploadBlob('sample', 'text', 'Hello World');

次に、Blob storage内のファイルをダウンロードして、ローカルに保存します。

download
const { BlobServiceClient } = require('@azure/storage-blob');
const fs = require('fs');
const path = require('path');

async function downloadBlobToFile(containerName, blobName, downloadFilePath) {
    // BlobServiceClientインスタンスを作成
    const blobServiceClient = BlobServiceClient.fromConnectionString(process.env.AZURE_STORAGE_CONNECTION_STRING);
    const containerClient = blobServiceClient.getContainerClient(containerName);
    const blobClient = containerClient.getBlobClient(blobName);

    // ブロブのダウンロード
    const downloadBlockBlobResponse = await blobClient.download();

    // ダウンロードしたブロブの内容をローカルのファイルに書き込む
    const destination = path.join(downloadFilePath, blobName);
    const stream = fs.createWriteStream(destination);
    downloadBlockBlobResponse.readableStreamBody.pipe(stream);

    return new Promise((resolve, reject) => {
        stream.on('finish', () => {
            console.log('Download Success');
            resolve(destination);
        });

        stream.on('error', (error) => {
            console.error("Error writing blob to file", error);
            reject(error);
        });
    });
}

// 関数を呼び出し、'sample'コンテナ内の'text'ブロブをローカルファイルにダウンロード
downloadBlobToFile('sample', 'text', './downloads').catch(console.error)

時間があれば、SASトークン(制限付きアクセス)によるダウンロードも書きます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0