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

本快速入门介绍如何使用完全在浏览器中运行的 JavaScript 代码来管理 Blob。In this quickstart, you learn to manage blobs by using JavaScript code running entirely in the browser. Blob 是可以保存大量文本或二进制数据(包括图像、文档、流媒体和存档数据)的对象。Blobs are objects that can hold large amounts of text or binary data, including images, documents, streaming media, and archive data. 你将采取必要的安全措施来确保对 Blob 存储帐户的访问受到保护。You'll use required security measures to ensure protected access to your blob storage account.

备注

此快速启动使用 Azure Blob 存储客户端库的旧版本。This quickstart uses a legacy version of the Azure Blob storage client library. 若要开始使用最新版本,请参阅快速入门:在浏览器中使用 JavaScript v12 SDK 管理 BlobTo get started with the latest version, see Quickstart: Manage blobs with JavaScript v12 SDK in a browser.

先决条件Prerequisites

设置存储帐户 CORS 规则Setting up storage account CORS rules

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

返回到 Azure 门户,然后选择存储帐户。Return to the Azure portal and select your storage account. 若要定义新的 CORS 规则,请导航到“设置”部分,然后单击“CORS”链接。To define a new CORS rule, navigate to the Settings section and click on the CORS link. 对于本快速入门,请创建开放的 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 Value 说明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 和 putdelete, 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 (seconds) 8640086400 浏览器缓存预检 OPTIONS 请求的最长时间。The maximum amount of time the browser caches the preflight OPTIONS request. 值为 86400 意味着缓存可以保留一整天。A value of 86400 allows the cache to remain for a full day.

重要

请确保将生产环境中使用的任何设置所公开的针对存储帐户的访问权限降至最低,以便始终能够进行安全的访问。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.

接下来,使用 Azure CLI 创建一个安全令牌。Next, you use the Azure cli to create a security token.

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

在浏览器中运行的代码可以使用共享访问签名 (SAS) 对发往 Blob 存储的请求进行授权。The shared access signature (SAS) is used by the code running in the browser to authorize requests to Blob storage. 使用 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).

可以使用 Azure CLI、Azure 门户或 Azure 存储资源管理器来创建 SAS。You can create a SAS using the Azure CLI, or with the Azure portal or Azure Storage Explorer. 下表描述了使用 CLI 生成 SAS 时需要提供值的参数。The following table describes the parameters you need to provide values for to generate a SAS with the CLI.

参数Parameter 说明Description 占位符Placeholder
expiryexpiry 访问令牌的过期日期,采用 YYYY-MM-DD 格式。The expiration date of the access token in YYYY-MM-DD format. 若要在本快速入门中使用,请输入明天的日期。Enter tomorrow's date for use with this quickstart. FUTURE_DATEFUTURE_DATE
account-nameaccount-name 存储帐户名称。The storage account name. 请使用在此前的步骤中搁置的名称。Use the name set aside in an earlier step. YOUR_STORAGE_ACCOUNT_NAMEYOUR_STORAGE_ACCOUNT_NAME
account-keyaccount-key 存储帐户密钥。The storage account key. 请使用在此前的步骤中搁置的密钥。Use the key set aside in an earlier step. YOUR_STORAGE_ACCOUNT_KEYYOUR_STORAGE_ACCOUNT_KEY

使用以下 CLI 命令(请将每个占位符替换为实际值)生成可在 JavaScript 代码中使用的 SAS。Use the following CLI command, with actual values for each placeholder, to generate a SAS that you can use in your JavaScript code.

az storage account generate-sas \
  --permissions racwdl \
  --resource-types sco \
  --services b \
  --expiry FUTURE_DATE \
  --account-name YOUR_STORAGE_ACCOUNT_NAME \
  --account-key YOUR_STORAGE_ACCOUNT_KEY

你可能会觉得每个参数之后的一系列值有点费解。You may find the series of values after each parameter a bit cryptic. 这些参数值取自相应权限的第一个字母。These parameter values are taken from the first letter of their respective permission. 下表解释了这些值的来源:The following table explains where the values come from:

参数Parameter Value 说明Description
权限permissions racwdlracwdl 此 SAS 允许 read(读取)、append(追加)、create(创建)、write(编写)、delete(删除)和 list(列出)功能。This SAS allows read, append, create, write, delete, and list capabilities.
resource-typesresource-types scosco 受 SAS 影响的资源为 service(服务)、container(容器)和 object(对象)。The resources affected by the SAS are service, container, and object.
servicesservices bb 受 SAS 影响的服务为 blob 服务。The service affected by the SAS is the blob service.

生成 SAS 后,复制返回值并将其保存到某个位置,以便在后续步骤中使用。Now that the SAS is generated, copy the return value and save it somewhere for use in an upcoming step. 如果使用 Azure CLI 以外的方法生成了 SAS,则需要删除初始的 ?(如果存在)。If you generated your SAS using a method other than the Azure CLI, you will need to remove the initial ? if it is present. 此字符是已在 URL 模板中提供的 URL 分隔符,本主题稍后用到 SAS 的步骤都会使用它。This character is a URL separator that is already provided in the URL template later in this topic where the SAS is used.

重要

在生产环境中,请始终使用 TLS 来传递 SAS 令牌。In production, always pass SAS tokens using TLS. 另外,SAS 令牌应该在服务器上生成并发送到 HTML 页面,以便将其传递回 Azure Blob 存储。Also, SAS tokens should be generated on the server and sent to the HTML page in order pass back to Azure Blob Storage. 一种可以考虑的方法是使用无服务器函数来生成 SAS 令牌。One approach you may consider is to use a serverless function to generate SAS tokens. Azure 门户包括的函数模板具有通过 JavaScript 函数生成 SAS 的功能。The Azure Portal includes function templates that feature the ability to generate a SAS with a JavaScript function.

实现 HTML 页Implement the HTML page

在本部分,你将创建一个基本的网页,然后将 VS Code 配置为启动并调试该页面。In this section, you'll create a basic web page and configure VS Code to launch and debug the page. 但是,在启动之前,需要使用 Node.js 启动本地 Web 服务器,并根据浏览器的请求提供该页面。Before you can launch, however, you'll need to use Node.js to start a local web server and serve the page when your browser requests it. 接下来,添加 JavaScript 代码以调用各种 Blob 存储 API,并在页中显示结果。Next, you'll add JavaScript code to call various blob storage APIs and display the results in the page. 也可以在 Azure 门户Azure 存储资源管理器和适用于 VS Code 的 Azure 存储扩展中查看这些调用的结果。You can also see the results of these calls in the Azure portal, Azure Storage Explorer, and the Azure Storage extension for VS Code.

设置 Web 应用程序Set up the web application

首先,创建名为 azure-blob-javascript 的新文件夹并在 VS Code 中打开它。First, create a new folder named azure-blobs-javascript and open it in VS Code. 然后在 VS Code 中创建一个新文件,添加以下 HTML,并在 azure-blob-javascript 文件夹中将其保存为 index.htmlThen create a new file in VS Code, add the following HTML, and save it as index.html in the azure-blobs-javascript folder.

<!DOCTYPE html>
<html>

<body>
    <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><b>Status:</b></p>
    <p id="status" style="height:160px; width: 593px; overflow: scroll;" />
    <p><b>Files:</b></p>
    <select id="file-list" multiple style="height:222px; width: 593px; overflow: scroll;" />
</body>

<!-- You'll add code here later in this quickstart. -->

</html>

配置调试器Configure the debugger

若要在 VS Code 中设置调试器扩展,请选择“调试”>“添加配置...”,然后根据在前面“先决条件”部分选择的扩展,选择“Chrome”或“Microsoft Edge”。To set up the debugger extension in VS Code, select Debug > Add Configuration..., then select Chrome or Edge, depending on which extension you installed in the Prerequisites section earlier. 此操作会创建 launch.json 文件并在编辑器中打开它。This action creates a launch.json file and opens it in the editor.

接下来,修改 launch.json 文件,使 url 值包含 /index.html,如下所示:Next, modify the launch.json file so that the url value includes /index.html as shown:

{
    // 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": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:8080/index.html",
            "webRoot": "${workspaceFolder}"
        }
    ]
}

此配置告知 VS Code 要启动哪个浏览器以及要加载哪个 URL。This configuration tells VS Code which browser to launch and which URL to load.

启动 Web 服务器Launch the web server

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

npx http-server

此命令将安装 http-server 包并启动服务器,以便可以通过默认的 URL 使用当前文件夹(包括上一步骤中所示的文件夹)。This command will install the http-server package and launch the server, making the current folder available through default URLs including the one indicated in the previous step.

开始调试Start debugging

若要在附加了 VS Code 调试器的浏览器中启动 index.html,请选择“调试”>“开始调试”,或者在 VS Code 中按 F5。To launch index.html in the browser with the VS Code debugger attached, select Debug > Start Debugging or press F5 in VS Code.

显示的 UI 暂时不起任何作用,但在下一部分,你将会添加 JavaScript 代码以实现所示的每个函数。The UI displayed doesn't do anything yet, but you'll add JavaScript code in the following section to implement each function shown. 然后可以设置断点,并在调试器在代码中暂停时与它交互。You can then set breakpoints and interact with the debugger when it's paused on your code.

index.html 进行更改后,请务必重新加载页面,以便在浏览器中查看更改。When you make changes to index.html, be sure to reload the page to see the changes in the browser. 在 VS Code 中,还可以选择“调试”>“重新开始调试”,或按 CTRL + SHIFT + F5。In VS Code, you can also select Debug > Restart Debugging or press CTRL + SHIFT + F5.

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

若要调用 Blob 存储 API,请先下载适用于 JavaScript 的 Azure 存储 SDK - Blob 客户端库,提取压缩内容,并将 azure-storage.blob.js 文件放入 azure-blob-javascript 文件夹 。To enable calls to the blob storage API, first Download the Azure Storage SDK for JavaScript - Blob client library, extract the contents of the zip, and place the azure-storage-blob.js file in the azure-blobs-javascript folder.

接下来,将以下 HTML 粘贴到 index.html 中的 </body> 结束标记的后面(请替换占位符注释)。Next, paste the following HTML into index.html after the </body> closing tag, replacing the placeholder comment.

<script src="azure-storage-blob.js" charset="utf-8"></script>

<script>
// You'll add code here in the following sections.
</script>

此代码添加对脚本文件的引用,并为你自己的 JavaScript 代码提供一个位置。This code adds a reference to the script file and provides a place for your own JavaScript code. 在本快速入门中,我们将使用 azure-storage.blob.js 脚本文件,以便可以在 VS Code 中打开它、读取其内容,并设置断点。For the purposes of this quickstart, we're using the azure-storage-blob.js script file so that you can open it in VS Code, read its contents, and set breakpoints. 在生产环境中,应使用更精简的 azure-storage.blob.min.js 文件,该文件也已在 zip 文件中提供。In production, you should use the more compact azure-storage.blob.min.js file that is also provided in the zip file.

可以在参考文档中详细了解每个 Blob 存储函数。You can find out more about each blob storage function in the reference documentation. 请注意,SDK 中的某些函数只能在 Node.js 中使用,或只能在浏览器中使用。Note that some of the functions in the SDK are only available in Node.js or only available in the browser.

azure-storage.blob.js 中的代码导出名为 azblob 的全局变量,你将在 JavaScript 代码中使用该变量来访问 Blob 存储 API。The code in azure-storage-blob.js exports a global variable called azblob, which you'll use in your JavaScript code to access the blob storage APIs.

添加初始 JavaScript 代码Add the initial JavaScript code

接下来,将以下代码粘贴到上一个代码块中所示的 <script> 元素(请替换占位符注释)。Next, paste the following code into the <script> element shown in the previous code block, replacing the placeholder comment.

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;
}

此代码为后续代码要使用的每个 HTML 元素创建字段,并实现一个 reportStatus 函数来显示输出。This code creates fields for each HTML element that the following code will use, 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

接下来,添加用于访问存储帐户的代码(请将占位符替换为你的帐户名称和上一步骤中生成的 SAS)。Next, add code to access your storage account, replacing the placeholders with your account name and the SAS you generated in a previous step.

const accountName = "<Add your storage account name>";
const sasString = "<Add the SAS you generated earlier>";
const containerName = "testcontainer";
const containerURL = new azblob.ContainerURL(
    `https://${accountName}.blob.core.chinacloudapi.cn/${containerName}?${sasString}`,
    azblob.StorageURL.newPipeline(new azblob.AnonymousCredential));

此代码使用你的帐户信息和 SAS 来创建 ContainerURL 实例,该实例可用于创建和操作存储容器。This code uses your account info and SAS to create a ContainerURL instance, which is useful for creating and manipulating a storage container.

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

接下来,添加可在按下相应按钮时创建和删除存储容器的代码。Next, add code to create and delete the storage container when you press the corresponding button.

const createContainer = async () => {
    try {
        reportStatus(`Creating container "${containerName}"...`);
        await containerURL.create(azblob.Aborter.none);
        reportStatus(`Done.`);
    } catch (error) {
        reportStatus(error.body.message);
    }
};

const deleteContainer = async () => {
    try {
        reportStatus(`Deleting container "${containerName}"...`);
        await containerURL.delete(azblob.Aborter.none);
        reportStatus(`Done.`);
    } catch (error) {
        reportStatus(error.body.message);
    }
};

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

此代码在不使用 Aborter 实例的情况下调用 ContainerURL createdelete 函数。This code calls the ContainerURL create and delete functions without using an Aborter instance. 为了简化本快速入门中的操作,此代码假设你的存储帐户已创建且已启用。To keep things simple for this quickstart, this code assumes that your storage account has been created and is enabled. 在生产代码中,请使用 Aborter 实例来添加超时功能。In production code, use an Aborter instance to add timeout functionality.

列出 BlobList blobs

接下来,添加可在按下“List files”按钮时列出存储容器内容的代码。Next, add code to list the contents of the storage container when you press the List files button.

const listFiles = async () => {
    fileList.size = 0;
    fileList.innerHTML = "";
    try {
        reportStatus("Retrieving file list...");
        let marker = undefined;
        do {
            const listBlobsResponse = await containerURL.listBlobFlatSegment(
                azblob.Aborter.none, marker);
            marker = listBlobsResponse.nextMarker;
            const items = listBlobsResponse.segment.blobItems;
            for (const blob of items) {
                fileList.size += 1;
                fileList.innerHTML += `<option>${blob.name}</option>`;
            }
        } while (marker);
        if (fileList.size > 0) {
            reportStatus("Done.");
        } else {
            reportStatus("The container does not contain any files.");
        }
    } catch (error) {
        reportStatus(error.body.message);
    }
};

listButton.addEventListener("click", listFiles);

此代码将在循环中调用 ContainerURL.listBlobFlatSegment 函数,以确保检索所有段。This code calls the ContainerURL.listBlobFlatSegment function in a loop to ensure that all segments are retrieved. 对于每个段,它会循环访问它所包含的 Blob 项列表,并更新 Files 列表。For each segment, it loops over the list of blob items it contains and updates the Files list.

上传 BlobUpload blobs

接下来,添加可在按下“Select and upload files”按钮时将文件上传到存储容器的代码。Next, add code to upload files to the storage container when you press the Select and upload files button.

const uploadFiles = async () => {
    try {
        reportStatus("Uploading files...");
        const promises = [];
        for (const file of fileInput.files) {
            const blockBlobURL = azblob.BlockBlobURL.fromContainerURL(containerURL, file.name);
            promises.push(azblob.uploadBrowserDataToBlockBlob(
                azblob.Aborter.none, file, blockBlobURL));
        }
        await Promise.all(promises);
        reportStatus("Done.");
        listFiles();
    } catch (error) {
        reportStatus(error.body.message);
    }
}

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

此代码将“Select and upload files”按钮连接到隐藏的 file-input 元素。This code connects the Select and upload files button to the hidden file-input element. 这样,按钮 click 事件便会触发文件输入 click 事件,并显示文件选取器。In this way, 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. 对于选择的每个文件,此函数将调用仅限浏览器的 uploadBrowserDataToBlockBlob 函数。This function calls the browser-only uploadBrowserDataToBlockBlob function for each file you selected. 每次调用都会返回一个约定,此约定将添加到某个列表,以便可以等待一次,导致并行上传文件。Each call returns a Promise, which is added to a list so that they can all be awaited at once, causing the files to upload in parallel.

删除 BlobDelete blobs

接下来,添加可在按下“Delete selected files”按钮时从存储容器中删除文件的代码。Next, add code to delete files from the storage container when you press the Delete selected files button.

const deleteFiles = async () => {
    try {
        if (fileList.selectedOptions.length > 0) {
            reportStatus("Deleting files...");
            for (const option of fileList.selectedOptions) {
                const blobURL = azblob.BlobURL.fromContainerURL(containerURL, option.text);
                await blobURL.delete(azblob.Aborter.none);
            }
            reportStatus("Done.");
            listFiles();
        } else {
            reportStatus("No files selected.");
        }
    } catch (error) {
        reportStatus(error.body.message);
    }
};

deleteButton.addEventListener("click", deleteFiles);

此代码调用 BlobURL.delete 函数以删除列表中选择的每个文件。This code calls the BlobURL.delete 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.

运行并测试 Web 应用程序Run and test the web application

现在,可以启动该页面并试着体会 Blob 存储的工作方式。At this point, you can launch the page and experiment to get a feel for how blob storage works. 如果发生任何错误(例如,在创建容器之前尝试列出文件时),“状态”窗格将显示收到的错误消息。If any errors occur (for example, when you try to list files before you've created the container), the Status pane will display the error message received. 还可以在 JavaScript 代码中设置断点,以检查存储 API 返回的值。You can also set breakpoints in the JavaScript code to examine the values returned by the storage APIs.

清理资源Clean up resources

若要清理在本快速入门中创建的资源,请转到 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've created a simple website that accesses blob storage from browser-based JavaScript. 若要了解如何在 Blob 存储中托管网站本身,请继续阅读以下教程:To learn how you can host a website itself on blob storage, continue to the following tutorial: