Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit editor mode

Quickstart: Manage blobs with JavaScript v12 SDK in a browser

Feedback

In this article

Azure Blob storage is optimized for storing large amounts of unstructured data. Blobs are objects that can hold text or binary data, including images, documents, streaming media, and archive data. In this quickstart, you learn to manage blobs by using JavaScript in a browser. You'll upload and list blobs, and you'll create and delete containers.

Theexample code shows you how to accomplish the following tasks with the Azure Blob storage client library for #"#declare-fields-for-ui-elements" data-linktype="self-bookmark">Declare fields for UI elements

  • Add your storage account info
  • Create client objects
  • Create and delete a storage container
  • List blobs
  • Upload blobs
  • Delete blobs
  • Additional resources:

    API reference |Library source code |Package (npm) |Samples

    Prerequisites

    Object model

    Blob storage offers three types of resources:

    • The storage account
    • A container in the storage account
    • A blob in the container

    The following diagram shows the relationship between these resources.

    Diagram of Blob storage architecture

    In this quickstart, you'll use the following JavaScript classes to interact with these resources:

    • BlobServiceClient: TheBlobServiceClient class allows you to manipulate Azure Storage resources and blob containers.
    • ContainerClient: TheContainerClient class allows you to manipulate Azure Storage containers and their blobs.
    • BlockBlobClient: TheBlockBlobClient class allows you to manipulate Azure Storage blobs.

    Configure storage account for browser access

    To programmatically access your storage account from a web browser, you need to configure CORS access and create an SAS connection string.

    Create a CORS rule

    Before your web application can access blob storage from the client, you must configure your account to enablecross-origin resource sharing, or CORS.

    In the Azure portal, select your storage account. To define a new CORS rule, navigate to theSettings section and selectCORS. For this quickstart, you create a fully-open CORS rule:

    Azure Blob Storage Account CORS settings

    The following table describes each CORS setting and explains the values used to define the rule.

    SettingValueDescription
    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 METHODSDELETE,GET,HEAD,MERGE,POST,OPTIONS, andPUTLists 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 AGE86400The maximum amount of time the browser caches the preflight OPTIONS request in seconds. A value of86400 allows the cache to remain for a full day.

    After you fill in the fields with the values from this table, select theSave button.

    Important

    Ensure any settings you use in production expose the minimum amount of access necessary to your storage account to maintain secure access. 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 SAS connection string

    The shared access signature (SAS) is used by code running in the browser to authorize Azure Blob storage requests. By using the SAS, the client can authorize access to storage resources without the account access key or connection string. For more information on SAS, seeUsing shared access signatures (SAS).

    Follow these steps to get the Blob service SAS URL:

    1. In the Azure portal, select your storage account.
    2. Navigate to theSecurity + networking section and selectShared access signature.
    3. Review theAllowed services to understand the SAS token will have access to all of your storage account services:
      • Blob
      • File
      • Queue
      • Table
    4. Select theAllowed resources types to include:
      • Service
      • Container
      • Object
    5. Review theStart and expiry date/time to understand the SAS token has a limited lifetime by default.
    6. Scroll down and select theGenerate SAS and connection string button.
    7. Scroll down further and locate theBlob service SAS URL field
    8. Select theCopy to clipboard button at the far-right end of theBlob service SAS URL field.
    9. Save the copied URL somewhere for use in an upcoming step.

    Note

    The SAS token returned by the portal does not include the delimiter character ('?') for the URL query string. If you are appending the SAS token to a resource URL, remember to append the delimiter character to the resource URL before appending the SAS token.

    Create the JavaScript project

    Create a JavaScript application namedblob-quickstart-v12.

    1. In a console window (such as cmd, PowerShell, or Bash), create a new directory for the project.

      mkdir blob-quickstart-v12
    2. Switch to the newly createdblob-quickstart-v12 directory.

      cd blob-quickstart-v12
    3. Create apackage.json.

      npm init -y
    4. Open the project in Visual Studio Code:

      code .

    Install the npm package for blob storage

    1. In a Visual Studio Code terminal, install the Azure Storage npm package:

      npm install @azure/storage-blob
    2. Install a bundler package to bundle the files and package for the browser:

      npm install parcel

      If you plan to use a different bundler, learn more aboutbundling the Azure SDK.

    Configure browser bundling

    1. In Visual Studio Code, open thepackage.json file and add abrowserlist. Thisbrowserlist targets the latest version of popular browsers. The fullpackage.json file should now look like this:

      "browserslist": [  "last 1 Edge version",  "last 1 Chrome version",  "last 1 Firefox version",  "last 1 safari version",  "last 1 webkit version"],
    2. Add astart script to bundle the website:

      "scripts": {  "start": "parcel ./index.html"},

    Create the HTML file

    1. Createindex.html and add the following HTML code:

      <!-- index.html --><!DOCTYPE html><html><body>    <button>Create container</button>    <button>Select and upload files</button>    <input type="file" multiple />    <button>List files</button>    <button>Delete selected files</button>    <button>Delete container</button>    <p><b>Status:</b></p>    <p />    <p><b>Files:</b></p>    <select multiple /></body><script type="module" src="./index.js"></script></html>

    Create the JavaScript file

    From the project directory:

    1. Create a new file namedindex.js.

    2. Add the Azure Storage npm package.

      const { BlobServiceClient } = require("@azure/storage-blob");

    Declare fields for UI elements

    Add DOM elements for user interaction:

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

    This code declares fields for each HTML element and implements areportStatus function to display output.

    Add your storage account info

    Add the following code at the end of theindex.js file to access your storage account. Replace the<placeholder> with your Blob service SAS URL that you generated earlier. Add the following code to the end of theindex.js file.

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

    Create client objects

    CreateBlobServiceClient andContainerClient objects to connect to your storage account. Add the following code to the end of theindex.js file.

    // Create a new BlobServiceClientconst blobServiceClient = new BlobServiceClient(blobSasUrl);// Create a unique name for the container by // appending the current time to the file nameconst containerName = "container" + new Date().getTime();// Get a container client from the BlobServiceClientconst containerClient = blobServiceClient.getContainerClient(containerName);

    Create and delete a storage container

    Create and delete the storage container when you select the corresponding button on the web page. Add the following code to the end of theindex.js file.

    const createContainer = async () => {    try {        reportStatus(`Creating container "${containerName}"...`);        await containerClient.create();        reportStatus(`Done. URL:${containerClient.url}`);    } catch (error) {        reportStatus(error.message);    }};const deleteContainer = async () => {    try {        reportStatus(`Deleting container "${containerName}"...`);        await containerClient.delete();        reportStatus(`Done.`);    } catch (error) {        reportStatus(error.message);    }};createContainerButton.addEventListener("click", createContainer);deleteContainerButton.addEventListener("click", deleteContainer);

    List blobs

    List the contents of the storage container when you select theList files button. Add the following code to the end of theindex.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) {            reportStatus("Done.");        } else {            reportStatus("The container does not contain any files.");        }    } catch (error) {        reportStatus(error.message);    }};listButton.addEventListener("click", listFiles);

    This code calls theContainerClient.listBlobsFlat function, then uses an iterator to retrieve the name of eachBlobItem returned. For eachBlobItem, it updates theFiles list with thename property value.

    Upload blobs to a container

    Upload files to the storage container when you select theSelect and upload files button. Add the following code to the end of theindex.js file.

    const uploadFiles = async () => {    try {        reportStatus("Uploading files...");        const promises = [];        for (const file of fileInput.files) {            const blockBlobClient = containerClient.getBlockBlobClient(file.name);            promises.push(blockBlobClient.uploadBrowserData(file));        }        await Promise.all(promises);        reportStatus("Done.");        listFiles();    }    catch (error) {            reportStatus(error.message);    }}selectButton.addEventListener("click", () => fileInput.click());fileInput.addEventListener("change", uploadFiles);

    This code connects theSelect and upload files button to the hiddenfile-input element. The buttonclick event triggers the file inputclick event and displays the file picker. After you select files and close the dialog box, theinput event occurs and theuploadFiles function is called. This function creates aBlockBlobClient object, then calls the browser-onlyuploadBrowserData function for each file you selected. Each call returns aPromise. EachPromise is added to a list so that they can all be awaited together, causing the files to upload in parallel.

    Delete blobs

    Delete files from the storage container when you select theDelete selected files button. Add the following code to the end of theindex.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);            }            reportStatus("Done.");            listFiles();        } else {            reportStatus("No files selected.");        }    } catch (error) {        reportStatus(error.message);    }};deleteButton.addEventListener("click", deleteFiles);

    This code calls theContainerClient.deleteBlob function to remove each file selected in the list. It then calls thelistFiles function shown earlier to refresh the contents of theFiles list.

    Run the code

    1. From a Visual Studio Code terminal, run the app.

      npm start

      This process bundles the files and starts a web server.

    2. Access the web site with a browser using the following URL:

      http://localhost:1234

    Step 1: Create a container

    1. In the web app, selectCreate container. The status indicates that a container was created.
    2. In the Azure portal, verify your container was created. Select your storage account. UnderBlob service, selectContainers. Verify that the new container appears. (You may need to selectRefresh.)

    Step 2: Upload a blob to the container

    1. On your local computer, create and save a test file, such astest.txt.
    2. In the web app, selectSelect and upload files.
    3. Browse to your test file, and then selectOpen. The status indicates that the file was uploaded, and the file list was retrieved.
    4. In the Azure portal, select the name of the new container that you created earlier. Verify that the test file appears.

    Step 3: Delete the blob

    1. In the web app, underFiles, select the test file.
    2. SelectDelete selected files. The status indicates that the file was deleted and that the container contains no files.
    3. In the Azure portal, selectRefresh. Verify that you seeNo blobs found.

    Step 4: Delete the container

    1. In the web app, selectDelete container. The status indicates that the container was deleted.
    2. In the Azure portal, select the<account-name> | Containers link at the top-left of the portal pane.
    3. SelectRefresh. The new container disappears.
    4. Close the web app.

    Use the storage emulator

    This quickstart created a container and blob on the Azure cloud. You can also use the Azure Blob storage npm package to create these resources locally on theAzure Storage emulator for development and testing.

    Clean up resources

    1. When you're done with this quickstart, delete theblob-quickstart-v12 directory.
    2. If you're done using your Azure Storage resource, remove your resource group using either method:

    Next steps

    In this quickstart, you learned how to upload, list, and delete blobs using JavaScript. You also learned how to create and delete a blob storage container.

    For tutorials, samples, quickstarts, and other documentation, visit:


    Feedback

    Was this page helpful?

    YesNoNo

    Need help with this topic?

    Want to try using Ask Learn to clarify or guide you through this topic?

    Suggest a fix?

    • Last updated on

    In this article

    Was this page helpful?

    YesNo
    NoNeed help with this topic?

    Want to try using Ask Learn to clarify or guide you through this topic?

    Suggest a fix?