Azure Blob Storage にファイルをアップロードする

Uncategorized
509 words

クライアント側だけで全て完結させます。

準備

Azure Blob Storage

事前に Azure Blob Storage にコンテナーを作成しておきます。

今回は次のような設定で作成しました。

  • ストレージ アカウント名:gorillabrs

  • Blob コンテナー名:images

Shared Access Signature (SAS)

今回は SAS を使って接続するため、事前に SASトークン を取得しておきます。

「SAS と接続文字列を生成する」を押すと SASトークン が発行されます。

CORS

クライアントがストレージ アカウントにアクセスできるように、CORSを構成します。

  • 許可されるオリジン: http://localhost:3000

  • 許可されたメソッド: パッチを除くすべて。

  • 許可されるヘッダー: *

  • 公開されるヘッダー: *

  • 最長有効期間: 86400

React

クライアント側は Reactフレームワーク を使います。

これは私が使いなれているからだけで、どんなフレームワークを使っても問題ありません。

次のコマンドで React のプロジェクトを作成しました。

1
2
3
npx create-react-app --template typescript myapp
cd myapp
npm run start

Azure Storage Blob client library for JavaScript

今回は Azure Storage Blob client library を使います。

1
npm install @azure/storage-blob

ソース

次のソースを App.tsx にコピペします。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { AnonymousCredential, ContainerClient } from '@azure/storage-blob';

function App() {

const clickedFileUpload = () => {

const target = document.getElementById("fileupload") as HTMLInputElement;
if (target.files == null || target.files.length <= 0) {
return;
}

const account = "gorillabrs";
const accountSas = "?sv=**********";
const containerName = "images";

const containerClient = new ContainerClient(
`https://${account}.blob.core.windows.net/${containerName}${accountSas}`,
new AnonymousCredential()
);

const file = target.files[0];

// コンテナ用の blobClient を作成する。
const blobClient = containerClient.getBlockBlobClient(file.name);

// ブラウザから判断した mimetype を設定する。
const options = { blobHTTPHeaders: { blobContentType: file.type } };

// ファイルアップロード
blobClient.uploadData(file, options).then(response => {
console.log("response:", response);
}).catch(error => {
console.log("error:", error);
});
}

return (
<div>
<input type="file" id="fileupload" />
<br /><br />
<button type="button" onClick={clickedFileUpload}>ファイルのアップロード</button>
</div>
);
}

export default App;

実行

アップロードしたいファイルを選択し、ファイルアップロードボタンを押すと Blob Storage にファイルがアップロードされます。

参考

https://learn.microsoft.com/ja-jp/azure/developer/javascript/tutorial/browser-file-upload-azure-storage-blob?tabs=typescript%2Cuser-delegated-sas

備考

Shared Access Signature (SAS)

Shared Access Signature (SAS)は、Microsoft Azureサービスに対するセキュアなアクセスを提供するための仕組みです。SASは、クライアントが特定のリソースに対する限定的なアクセス権を持つことを可能にします。