快速入门:在浏览器中使用 JavaScript v12 SDK 管理 BlobQuickstart: Manage blobs with JavaScript v12 SDK in a browser

Azure Blob 存储已经过优化,可以存储大量的非结构化数据。Azure Blob storage is optimized for storing large amounts of unstructured data. Blob 是可以保存文本或二进制数据(包括图像、文档、流媒体和存档数据)的对象。Blobs are objects that can hold text or binary data, including images, documents, streaming media, and archive data. 本快速入门介绍如何在浏览器中使用 JavaScript 管理 Blob。In this quickstart, you learn to manage blobs by using JavaScript in a browser. 你将上传和列出 Blob,并创建和删除容器。You'll upload and list blobs, and you'll create and delete containers.

其他资源:Additional resources:



本文中所述的功能现在可用于具有分层命名空间的帐户。The features described in this article are now available to accounts that have a hierarchical namespace. 若要查看限制,请参阅 Azure Data Lake Storage Gen2 中可用的 Blob 存储功能一文。To review limitations, see the Blob storage features available in Azure Data Lake Storage Gen2 article.

对象模型Object model

Blob 存储提供了三种类型的资源:Blob storage offers three types of resources:

  • 存储帐户The storage account
  • 存储帐户中的容器A container in the storage account
  • 容器中的 blobA blob in the container

以下图示显示了这些资源之间的关系。The following diagram shows the relationship between these resources.

Blob 存储体系结构的图示

在本快速入门中,你将使用以下 JavaScript 类来与这些资源进行交互:In this quickstart, you'll use the following JavaScript classes to interact with these resources:

  • BlobServiceClientBlobServiceClient 类可用于操纵 Azure 存储资源和 blob 容器。BlobServiceClient: The BlobServiceClient class allows you to manipulate Azure Storage resources and blob containers.
  • ContainerClientContainerClient 类可用于操纵 Azure 存储容器及其 blob。ContainerClient: The ContainerClient class allows you to manipulate Azure Storage containers and their blobs.
  • BlockBlobClientBlockBlobClient 类可用于操纵 Azure 存储 blob。BlockBlobClient: The BlockBlobClient class allows you to manipulate Azure Storage blobs.

设置Setting up

本部分逐步指导如何准备一个项目,使其与适用于 JavaScript 的 Azure Blob 存储客户端库 v12 配合使用。This section walks you through preparing a project to work with the Azure Blob storage client library v12 for JavaScript.

创建 CORS 规则Create a CORS rule

必须先配置你的帐户来启用跨源资源共享(简称 CORS),然后 Web 应用程序才能从客户端访问 Blob 存储。Before your web application can access blob storage from the client, you must configure your account to enable cross-origin resource sharing, or CORS.

在 Azure 门户中,选择你的存储帐户。In the Azure portal, select your storage account. 若要定义新的 CORS 规则,请导航到“设置”部分并选择“CORS”。 To define a new CORS rule, navigate to the Settings section and select CORS. 对于本快速入门,请创建开放的 CORS 规则:For this quickstart, you create an open CORS rule:

Azure Blob 存储帐户 CORS 设置

下表描述了每项 CORS 设置,并对用于定义规则的值进行了说明。The following table describes each CORS setting and explains the values used to define the rule.

设置Setting ValueValue 说明Description
允许的源ALLOWED ORIGINS * 接受一个逗号分隔的列表,其中的域设置为可以接受的域。Accepts a comma-delimited list of domains set as acceptable origins. 将值设置为 * 意味着所有域都可以访问存储帐户。Setting the value to * allows all domains access to the storage account.
允许的方法ALLOWED METHODS “DELETE”、“GET”、“HEAD”、“MERGE”、“POST”、“OPTIONS”和“PUT” DELETE, GET, HEAD, MERGE, POST, OPTIONS, and PUT 列出允许对存储帐户执行操作的 HTTP 谓词。Lists the HTTP verbs allowed to execute against the storage account. 对于本快速入门,请选择所有可用的选项。For the purposes of this quickstart, select all available options.
允许的标头ALLOWED HEADERS * 定义一个列表,其中包含存储帐户允许的请求标头(包括带前缀的标头)。Defines a list of request headers (including prefixed headers) allowed by the storage account. 将值设置为 * 意味着所有标头都可以进行访问。Setting the value to * allows all headers access.
公开的标头EXPOSED HEADERS * 列出帐户允许的响应标头。Lists the allowed response headers by the account. 将值设置为 * 意味着帐户可以发送任何标头。Setting the value to * allows the account to send any header.
最长时间MAX AGE 8640086400 浏览器缓存预检 OPTIONS 请求的最长时间(以秒为单位)。The maximum amount of time the browser caches the preflight OPTIONS request in seconds. 值为 86400 意味着缓存可以保留一整天。A value of 86400 allows the cache to remain for a full day.

使用此表中的值填写字段后,单击“保存”按钮。After you fill in the fields with the values from this table, click the Save button.


请确保将生产环境中使用的任何设置所公开的针对存储帐户的访问权限降至最低,以便始终能够进行安全的访问。Ensure any settings you use in production expose the minimum amount of access necessary to your storage account to maintain secure access. 此处描述的 CORS 设置适用于快速入门,因为快速入门定义的安全策略是宽松的。The CORS settings described here are appropriate for a quickstart as it defines a lenient security policy. 但是,不建议对实际环境使用这些设置。These settings, however, are not recommended for a real-world context.

创建共享访问签名Create a shared access signature

在浏览器中运行的代码使用共享访问签名 (SAS) 来向 Azure Blob 存储请求授权。The shared access signature (SAS) is used by code running in the browser to authorize Azure Blob storage requests. 使用 SAS 时,客户端可以在没有帐户访问密钥或连接字符串的情况下授权对存储资源的访问。By using the SAS, the client can authorize access to storage resources without the account access key or connection string. 有关 SAS 的详细信息,请参阅使用共享访问签名 (SAS)For more information on SAS, see Using shared access signatures (SAS).

按照以下步骤获取 Blob 服务 SAS URL:Follow these steps to get the Blob service SAS URL:

  1. 在 Azure 门户中,选择你的存储帐户。In the Azure portal, select your storage account.
  2. 导航到“设置”部分,并选择“共享访问签名”。 Navigate to the Settings section and select Shared access signature.
  3. 向下滚动,然后单击“生成 SAS 和连接字符串”按钮。Scroll down and click the Generate SAS and connection string button.
  4. 继续向下滚动,找到“Blob 服务 SAS URL”字段Scroll down further and locate the Blob service SAS URL field
  5. 单击“Blob 服务 SAS URL”字段最右侧的“复制到剪贴板”按钮。 Click the Copy to clipboard button at the far-right end of the Blob service SAS URL field.
  6. 将复制的 URL 保存到某个位置,以便在后续步骤中使用。Save the copied URL somewhere for use in an upcoming step.

添加 Azure Blob 存储客户端库Add the Azure Blob storage client library

在本地计算机上创建名为 azure-blobs-js-browser 的新文件夹,并在 Visual Studio Code 中将其打开。On your local computer, create a new folder called azure-blobs-js-browser and open it in Visual Studio Code.

选择“视图”>“终端”在 Visual Studio Code 中打开一个控制台窗口。Select View > Terminal to open a console window inside Visual Studio Code. 在终端窗口中运行以下 Node.js 包管理器 (npm) 命令,以创建 package.json 文件。Run the following Node.js Package Manager (npm) command in the terminal window to create a package.json file.

npm init -y

Azure SDK 由许多单独的包组成。The Azure SDK is composed of many separate packages. 可以根据你想要使用的服务选择所需的包。You can choose which packages you need based on the services you intend to use. 在终端窗口中运行以下 npm 命令,以安装 @azure/storage-blob 包。Run following npm command in the terminal window to install the @azure/storage-blob package.

npm install --save @azure/storage-blob

捆绑 Azure Blob 存储客户端库Bundle the Azure Blob storage client library

若要在网站上使用 Azure SDK 库,请转换代码,使其能够在浏览器中运行。To use Azure SDK libraries on a website, convert your code to work inside the browser. 使用称作“捆绑程序”的工具来执行此操作。You do this using a tool called a bundler. 绑定过程将提取使用 Node.js 约定编写的 JavaScript 代码,并将其转换为浏览器能够理解的格式。Bundling takes JavaScript code written using Node.js conventions and converts it into a format that's understood by browsers. 本快速入门文章使用 Parcel 捆绑程序。This quickstart article uses the Parcel bundler.

在终端窗口中运行以下 npm 命令来安装 Parcel:Install Parcel by running the following npm command in the terminal window:

npm install -g parcel-bundler

在 Visual Studio Code 中打开 package.json 文件,并在 licensedependencies 条目之间添加 browserlistIn Visual Studio Code, open the package.json file and add a browserlist between the license and dependencies entries. browserlist 针对三个流行浏览器的最新版本。This browserlist targets the latest version of three popular browsers. 现在,完整的 package.json 文件应如下所示:The full package.json file should now look like this:

  "name": "azure-blobs-javascript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "keywords": [],
  "author": "",
  "license": "ISC",
  "browserslist": [
    "last 1 Edge version",
    "last 1 Chrome version",
    "last 1 Firefox version"
  "dependencies": {
    "@azure/storage-blob": "^12.1.1"

保存 package.json 文件。Save the package.json file.

导入 Azure Blob 存储客户端库Import the Azure Blob storage client library

若要在 JavaScript 中使用 Azure SDK 库,请导入 @azure/storage-blob 包。To use Azure SDK libraries inside JavaScript, import the @azure/storage-blob package. 在 Visual Studio Code 中创建包含以下 JavaScript 代码的新文件。Create a new file in Visual Studio Code containing the following JavaScript code.

// index.js
const { BlobServiceClient } = require("@azure/storage-blob");
// Now do something interesting with BlobServiceClient

将该文件作为 index.js 保存到 azure-blobs-js-browser 目录中。 Save the file as index.js in the azure-blobs-js-browser directory.

实现 HTML 页Implement the HTML page

在 Visual Studio Code 中创建一个新文件并添加以下 HTML 代码。Create a new file in Visual Studio Code and add the following HTML code.

<!-- index.html -->
<!DOCTYPE html>

    <button id="create-container-button">Create container</button>
    <button id="delete-container-button">Delete container</button>
    <button id="select-button">Select and upload files</button>
    <input type="file" id="file-input" multiple style="display: none;" />
    <button id="list-button">List files</button>
    <button id="delete-button">Delete selected files</button>
    <p id="status" style="height:160px; width: 593px; overflow: scroll;" />
    <select id="file-list" multiple style="height:222px; width: 593px; overflow: scroll;" />

<script src="./index.js"></script>


将该文件作为 index.html 保存到 azure-blobs-js-browser 文件夹中。 Save the file as index.html in the azure-blobs-js-browser folder.

代码示例Code examples

该示例代码展示了如何使用适用于 JavaScript 的 Azure Blob 存储客户端库完成以下任务:The example code shows you how to accomplish the following tasks with the Azure Blob storage client library for JavaScript:

你将在向 index.js 文件添加所有代码片段后运行代码。You'll run the code after you add all the snippets to the index.js file.

声明 UI 元素的字段Declare fields for UI elements

在 index.js 文件的末尾添加以下代码。Add the following code to the end of the index.js file.

const createContainerButton = document.getElementById("create-container-button");
const deleteContainerButton = document.getElementById("delete-container-button");
const selectButton = document.getElementById("select-button");
const fileInput = document.getElementById("file-input");
const listButton = document.getElementById("list-button");
const deleteButton = document.getElementById("delete-button");
const status = document.getElementById("status");
const fileList = document.getElementById("file-list");

const reportStatus = message => {
    status.innerHTML += `${message}<br/>`;
    status.scrollTop = status.scrollHeight;

保存 index.js 文件。Save the index.js file.

此代码声明每个 HTML 元素的字段,并实现一个 reportStatus 函数来显示输出。This code declares fields for each HTML element and implements a reportStatus function to display output.

在以下部分,在上一个块的后面添加 JavaScript 代码的每个新块。In the following sections, add each new block of JavaScript code after the previous block.

添加存储帐户信息Add your storage account info

添加用于访问存储帐户的代码。Add code to access your storage account. 请将占位符替换为你之前生成的 Blob 服务 SAS URL。Replace the placeholder with your Blob service SAS URL that you generated earlier. 在 index.js 文件的末尾添加以下代码。Add the following code to the end of the index.js file.

// Update <placeholder> with your Blob service SAS URL string
const blobSasUrl = "<placeholder>";

保存 index.js 文件。Save the index.js file.

创建客户端对象Create client objects

创建用来与 Azure Blob 存储服务交互的 BlobServiceClientContainerClient 对象。Create BlobServiceClient and ContainerClient objects for interacting with the Azure Blob storage service. 在 index.js 文件的末尾添加以下代码。Add the following code to the end of the index.js file.

// Create a new BlobServiceClient
const blobServiceClient = new BlobServiceClient(blobSasUrl);

// Create a unique name for the container by 
// appending the current time to the file name
const containerName = "container" + new Date().getTime();

// Get a container client from the BlobServiceClient
const containerClient = blobServiceClient.getContainerClient(containerName);

保存 index.js 文件。Save the index.js file.

创建和删除存储容器Create and delete a storage container

在网页上单击相应的按钮时会创建和删除存储容器。Create and delete the storage container when you click the corresponding button on the web page. 在 index.js 文件的末尾添加以下代码。Add the following code to the end of the index.js file.

const createContainer = async () => {
    try {
        reportStatus(`Creating container "${containerName}"...`);
        await containerClient.create();
    } catch (error) {

const deleteContainer = async () => {
    try {
        reportStatus(`Deleting container "${containerName}"...`);
        await containerClient.delete();
    } catch (error) {

createContainerButton.addEventListener("click", createContainer);
deleteContainerButton.addEventListener("click", deleteContainer);

保存 index.js 文件。Save the index.js file.

列出 BlobList blobs

单击“列出文件”按钮时,会列出存储容器的内容。List the contents of the storage container when you click the List files button. 在 index.js 文件的末尾添加以下代码。Add the following code to the end of the index.js file.

const listFiles = async () => {
    fileList.size = 0;
    fileList.innerHTML = "";
    try {
        reportStatus("Retrieving file list...");
        let iter = containerClient.listBlobsFlat();
        let blobItem = await iter.next();
        while (!blobItem.done) {
            fileList.size += 1;
            fileList.innerHTML += `<option>${blobItem.value.name}</option>`;
            blobItem = await iter.next();
        if (fileList.size > 0) {
        } else {
            reportStatus("The container does not contain any files.");
    } catch (error) {

listButton.addEventListener("click", listFiles);

保存 index.js 文件。Save the index.js file.

此代码调用 ContainerClient.listBlobsFlat 函数,然后使用迭代器检索返回的每个 BlobItem 的名称。This code calls the ContainerClient.listBlobsFlat function, then uses an iterator to retrieve the name of each BlobItem returned. 对于每个 BlobItem,它会使用 name 属性值更新“文件”列表。For each BlobItem, it updates the Files list with the name property value.

上传 BlobUpload blobs

单击“选择并上传文件”按钮时,会将文件上传到存储容器。Upload files to the storage container when you click the Select and upload files button. 在 index.js 文件的末尾添加以下代码。Add the following code to the end of the index.js file.

const uploadFiles = async () => {
    try {
        reportStatus("Uploading files...");
        const promises = [];
        for (const file of fileInput.files) {
            const blockBlobClient = containerClient.getBlockBlobClient(file.name);
        await Promise.all(promises);
    catch (error) {

selectButton.addEventListener("click", () => fileInput.click());
fileInput.addEventListener("change", uploadFiles);

保存 index.js 文件。Save the index.js file.

此代码将“Select and upload files”按钮连接到隐藏的 file-input 元素。This code connects the Select and upload files button to the hidden file-input element. 按钮 click 事件会触发文件输入 click 事件,并显示文件选取器。The button click event triggers the file input click event and displays the file picker. 选择文件并关闭对话框之后,将发生 input 事件并调用 uploadFiles 函数。After you select files and close the dialog box, the input event occurs and the uploadFiles function is called. 此函数创建一个 BlockBlobClient 对象,然后针对所选的每个文件调用仅限浏览器的 uploadBrowserData 函数。This function creates a BlockBlobClient object, then calls the browser-only uploadBrowserData function for each file you selected. 每个调用返回一个 PromiseEach call returns a Promise. 每个 Promise 将添加到列表中,这样就可以等待它们集中到一起,实现文件并行上传。Each Promise is added to a list so that they can all be awaited together, causing the files to upload in parallel.

删除 BlobDelete blobs

单击“删除选定的文件”按钮时,会从存储容器中删除文件。Delete files from the storage container when you click the Delete selected files button. 在 index.js 文件的末尾添加以下代码。Add the following code to the end of the index.js file.

const deleteFiles = async () => {
    try {
        if (fileList.selectedOptions.length > 0) {
            reportStatus("Deleting files...");
            for (const option of fileList.selectedOptions) {
                await containerClient.deleteBlob(option.text);
        } else {
            reportStatus("No files selected.");
    } catch (error) {

deleteButton.addEventListener("click", deleteFiles);

保存 index.js 文件。Save the index.js file.

此代码调用 ContainerClient.deleteBlob 函数,以删除列表中选定的每个文件。This code calls the ContainerClient.deleteBlob function to remove each file selected in the list. 然后,它会调用前面所示的 listFiles 来刷新 Files 列表的内容。It then calls the listFiles function shown earlier to refresh the contents of the Files list.

运行代码Run the code

若要在 Visual Studio Code 调试器中运行代码,请为浏览器配置 launch.json 文件。To run the code inside the Visual Studio Code debugger, configure the launch.json file for your browser.

配置调试器Configure the debugger

若要在 Visual Studio Code 中设置调试器扩展,请执行以下操作:To set up the debugger extension in Visual Studio Code:

  1. 选择“运行”>“添加配置”Select Run > Add Configuration
  2. 根据在前面的先决条件部分中安装的扩展,选择“Microsoft Edge”、“Chrome”或“Firefox”。 Select Edge, Chrome, or Firefox, depending on which extension you installed in the Prerequisites section earlier.

添加新配置会创建 launch.json 文件并在编辑器中打开该文件。Adding a new configuration creates a launch.json file and opens it in the editor. 修改 launch.json 文件,使 url 值为 http://localhost:1234/index.html,如下所示:Modify the launch.json file so that the url value is http://localhost:1234/index.html, as shown here:

    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
            "type": "edge",
            "request": "launch",
            "name": "Launch Edge against localhost",
            "url": "http://localhost:1234/index.html",
            "webRoot": "${workspaceFolder}"

更新后,保存 launch.json 文件。After updating, save the launch.json file. 此配置告知 Visual Studio Code 要打开哪个浏览器以及要加载哪个 URL。This configuration tells Visual Studio Code which browser to open and which URL to load.

启动 Web 服务器Launch the web server

若要启动本地开发 Web 服务器,请选择“视图”>“终端”在 Visual Studio Code 中打开一个控制台窗口,然后输入以下命令。To launch the local development web server, select View > Terminal to open a console window inside Visual Studio Code, then enter the following command.

parcel index.html

Parcel 会捆绑你的代码,并在 http://localhost:1234/index.html 上为你的页面启动一个本地开发服务器。Parcel bundles your code and starts a local development server for your page at http://localhost:1234/index.html. 每当保存 index.js 文件时,对该文件所做的更改会自动生成,并反映在开发服务器上。Changes you make to index.js will automatically be built and reflected on the development server whenever you save the file.

如果有消息指出“无法使用所配置的端口 1234”,可以运行命令 parcel -p <port#> index.html 来更改端口。If you receive a message that says configured port 1234 could not be used, you can change the port by running the command parcel -p <port#> index.html. 在 launch.json 文件中,更新 URL 路径中的端口,使之匹配。In the launch.json file, update the port in the URL path to match.

开始调试Start debugging

在调试器中运行该页,并大致感受一下 Blob 存储的工作原理。Run the page in the debugger and get a feel for how blob storage works. 如果出现任何错误,网页上的“状态”窗格会显示收到的错误消息。If any errors occur, the Status pane on the web page will display the error message received.

若要在附加了 Visual Studio Code 调试器的浏览器中打开 index.html,请在 Visual Studio Code 中选择“运行”>“开始调试”或者按 F5。To open index.html in the browser with the Visual Studio Code debugger attached, select Run > Start Debugging or press F5 in Visual Studio Code.

使用 Web 应用Use the web app

Azure 门户中,可按以下步骤验证 API 调用的结果。In the Azure portal, you can verify the results of the API calls as you follow the steps below.

步骤 1 - 创建容器Step 1 - Create a container

  1. 在 Web 应用中,选择“创建容器”。In the web app, select Create container. 状态将指示已创建了一个容器。The status indicates that a container was created.
  2. 若要在 Azure 门户中进行验证,请选择你的存储帐户。To verify in the Azure portal, select your storage account. 在“Blob 服务”下,选择“容器”。 Under Blob service, select Containers. 验证是否显示了新容器。Verify that the new container appears. (可能需要选择“刷新”。)(You may need to select Refresh.)

步骤 2 - 将 Blob 上传到容器Step 2 - Upload a blob to the container

  1. 在本地计算机上,创建并保存一个测试文件,例如 test.txt。On your local computer, create and save a test file, such as test.txt.
  2. 在 Web 应用中,单击“选择并上传文件”。In the web app, click Select and upload files.
  3. 浏览到测试文件,然后选择“打开”。Browse to your test file, and then select Open. 状态将指示文件已上传,并已检索到文件列表。The status indicates that the file was uploaded, and the file list was retrieved.
  4. 在 Azure 门户中,选择前面创建的新容器的名称。In the Azure portal, select the name of the new container that you created earlier. 验证是否显示了测试文件。Verify that the test file appears.

步骤 3 - 删除 BlobStep 3 - Delete the blob

  1. 在 Web 应用中,在“文件”下,选择测试文件。In the web app, under Files, select the test file.
  2. 选择“删除选定的文件”。Select Delete selected files. 状态将指示该文件已删除,并且容器不包含任何文件。The status indicates that the file was deleted and that the container contains no files.
  3. 在 Azure 门户中选择“刷新”。In the Azure portal, select Refresh. 验证是否显示了“找不到任何 Blob”。Verify that you see No blobs found.

步骤 4 - 删除容器Step 4 - Delete the container

  1. 在 Web 应用中,选择“删除容器”。In the web app, select Delete container. 状态将指示容器已删除。The status indicates that the container was deleted.
  2. 在 Azure 门户中,选择门户窗格左上角的“<account-name> | 容器”链接。In the Azure portal, select the <account-name> | Containers link at the top-left of the portal pane.
  3. 选择“刷新”。Select Refresh. 新容器随即消失。The new container disappears.
  4. 关闭 Web 应用。Close the web app.

清理资源Clean up resources

在 Visual Studio Code 中单击“终端”控制台,并按 CTRL+C 停止 Web 服务器。Click on the Terminal console in Visual Studio Code and press CTRL+C to stop the web server.

若要清理在本快速入门中创建的资源,请转到 Azure 门户,并删除在先决条件部分中创建的资源组。To clean up the resources created during this quickstart, go to the Azure portal and delete the resource group you created in the Prerequisites section.

后续步骤Next steps

本快速入门介绍了如何使用 JavaScript 上传、列出和删除 Blob。In this quickstart, you learned how to upload, list, and delete blobs using JavaScript. 此外,还介绍了如何创建和删除 Blob 存储容器。You also learned how to create and delete a blob storage container.

有关教程、示例、快速入门和其他文档,请访问:For tutorials, samples, quickstarts, and other documentation, visit: