Skip to content

Commit 8469143

Browse files
authored
Merge pull request #109072 from mhopkins-msft/js-quickstart-browser
JavaScript quickstart for the browser
2 parents bf234da + f621f76 commit 8469143

File tree

5 files changed

+314
-1
lines changed

5 files changed

+314
-1
lines changed

.openpublishing.publish.config.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,11 @@
499499
"path_to_root": "azure-cosmosdb-java-v4-getting-started",
500500
"url": "https://github.com/Azure-Samples/azure-cosmos-java-getting-started",
501501
"branch": "master"
502+
},
503+
{
504+
"path_to_root": "azure-storage-snippets",
505+
"url": "https://github.com/azure-samples/AzureStorageSnippets",
506+
"branch": "master"
502507
}
503508
],
504509
"branch_target_mapping": {

articles/storage/blobs/TOC.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@
4949
href: storage-quickstart-blobs-nodejs.md
5050
- name: JavaScript (v10 SDK for Node.js)
5151
href: storage-quickstart-blobs-nodejs-legacy.md
52+
- name: JavaScript (v12 SDK for browser)
53+
href: quickstart-blobs-javascript-browser.md
5254
- name: JavaScript (v10 SDK for browser)
5355
href: storage-quickstart-blobs-javascript-client-libraries-legacy.md
5456
- name: Go

articles/storage/blobs/index.yml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,10 @@ landingContent:
103103
url: storage-quickstart-blobs-java.md
104104
- text: Azure Blob storage for Python
105105
url: storage-quickstart-blobs-python.md
106-
- text: Azure Blob storage for JavaScript
106+
- text: Azure Blob storage for JavaScript using Node.js
107107
url: storage-quickstart-blobs-nodejs.md
108+
- text: Azure Blob storage for JavaScript in a browser
109+
url: quickstart-blobs-javascript-browser.md
108110
- text: Route events to a web endpoint
109111
url: ../../event-grid/blob-event-quickstart-portal.md
110112
- text: Host a static website
70.8 KB
Loading
Lines changed: 304 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,304 @@
1+
---
2+
title: "Quickstart: Azure Blob storage library v12 - JavaScript in a browser"
3+
description: In this quickstart, you learn how to use the Azure Blob storage client library version 12 for JavaScript in a browser. You create a container and an object in Blob storage. Next, you learn how to list all of the blobs in a container. Finally, you learn how to delete blobs and delete a container.
4+
author: mhopkins-msft
5+
6+
ms.author: mhopkins
7+
ms.date: 04/18/2020
8+
ms.service: storage
9+
ms.subservice: blobs
10+
ms.topic: quickstart
11+
---
12+
13+
<!-- Customer intent: As a web application developer I want to interface with Azure Blob storage entirely on the client so that I can build a SPA application that is able to upload and delete files on blob storage. -->
14+
15+
# Quickstart: Manage blobs with JavaScript v12 SDK in a browser
16+
17+
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.
18+
19+
[API reference documentation](/javascript/api/@azure/storage-blob) | [Library source code](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/storage/storage-blob) | [Package (npm)](https://www.npmjs.com/package/@azure/storage-blob) | [Samples](https://docs.microsoft.com/azure/storage/common/storage-samples-javascript?toc=%2fazure%2fstorage%2fblobs%2ftoc.json#blob-samples)
20+
21+
> [!NOTE]
22+
> To get started with the previous SDK version, see [Quickstart: Manage blobs with JavaScript v10 SDK in Node.js](storage-quickstart-blobs-nodejs-legacy.md).
23+
24+
## Prerequisites
25+
26+
* [An Azure account with an active subscription](https://azure.microsoft.com/free/?ref=microsoft.com&utm_source=microsoft.com&utm_medium=docs&utm_campaign=visualstudio)
27+
* [An Azure Storage account](../common/storage-account-create.md)
28+
* [Node.js](https://nodejs.org)
29+
* [Microsoft Visual Studio Code](https://code.visualstudio.com)
30+
* A Visual Studio Code extension for browser debugging, such as:
31+
* [Debugger for Microsoft Edge](vscode:extension/msjsdiag.debugger-for-edge)
32+
* [Debugger for Chrome](vscode:extension/msjsdiag.debugger-for-chrome)
33+
* [Debugger for Firefox](vscode:extension/firefox-devtools.vscode-firefox-debug)
34+
35+
36+
[!INCLUDE [storage-multi-protocol-access-preview](../../../includes/storage-multi-protocol-access-preview.md)]
37+
38+
## Object model
39+
40+
Blob storage offers three types of resources:
41+
42+
* The storage account
43+
* A container in the storage account
44+
* A blob in the container
45+
46+
The following diagram shows the relationship between these resources.
47+
48+
![Diagram of Blob storage architecture](./media/storage-blobs-introduction/blob1.png)
49+
50+
In this quickstart, you'll use the following JavaScript classes to interact with these resources:
51+
52+
* [BlobServiceClient](/javascript/api/@azure/storage-blob/blobserviceclient): The `BlobServiceClient` class allows you to manipulate Azure Storage resources and blob containers.
53+
* [ContainerClient](/javascript/api/@azure/storage-blob/containerclient): The `ContainerClient` class allows you to manipulate Azure Storage containers and their blobs.
54+
* [BlockBlobClient](/javascript/api/@azure/storage-blob/blockblobclient): The `BlockBlobClient` class allows you to manipulate Azure Storage blobs.
55+
56+
## Setting up
57+
58+
This section walks you through preparing a project to work with the Azure Blob storage client library v12 for JavaScript.
59+
60+
### Create a CORS rule
61+
62+
Before your web application can access blob storage from the client, you must configure your account to enable [cross-origin resource sharing](https://docs.microsoft.com/rest/api/storageservices/cross-origin-resource-sharing--cors--support-for-the-azure-storage-services), or CORS.
63+
64+
In the Azure portal, select your storage account. To define a new CORS rule, navigate to the **Settings** section and select **CORS**. For this quickstart, you create an open CORS rule:
65+
66+
![Azure Blob Storage Account CORS settings](media/quickstart-blobs-javascript-browser/azure-blob-storage-cors-settings.png)
67+
68+
The following table describes each CORS setting and explains the values used to define the rule.
69+
70+
|Setting |Value | Description |
71+
|---------|---------|---------|
72+
| **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. |
73+
| **ALLOWED METHODS** | **DELETE**, **GET**, **HEAD**, **MERGE**, **POST**, **OPTIONS**, and **PUT** | Lists the HTTP verbs allowed to execute against the storage account. For the purposes of this quickstart, select all available options. |
74+
| **ALLOWED HEADERS** | **\*** | Defines a list of request headers (including prefixed headers) allowed by the storage account. Setting the value to `*` allows all headers access. |
75+
| **EXPOSED HEADERS** | **\*** | Lists the allowed response headers by the account. Setting the value to `*` allows the account to send any header. |
76+
| **MAX AGE** | **86400** | The maximum amount of time the browser caches the preflight OPTIONS request in seconds. A value of *86400* allows the cache to remain for a full day. |
77+
78+
After you fill in the fields with the values from this table, click the **Save** button.
79+
80+
> [!IMPORTANT]
81+
> 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.
82+
83+
### Create a shared access signature
84+
85+
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, see [Using shared access signatures (SAS)](../common/storage-sas-overview.md).
86+
87+
Follow these steps to get the Blob service SAS URL:
88+
89+
1. In the Azure portal, select your storage account.
90+
2. Navigate to the **Settings** section and select **Shared access signature**.
91+
3. Scroll down and click the **Generate SAS and connection string** button.
92+
4. Scroll down further and locate the **Blob service SAS URL** field
93+
5. Click the **Copy to clipboard** button at the far-right end of the **Blob service SAS URL** field.
94+
6. Save the copied URL somewhere for use in an upcoming step.
95+
96+
### Add the Azure Blob storage client library
97+
98+
On your local computer, create a new folder called *azure-blobs-js-browser* and open it in Visual Studio Code.
99+
100+
Select **View > Terminal** to open a console window inside Visual Studio Code. Run the following Node.js Package Manager (npm) command in the terminal window to create a [package.json](https://docs.npmjs.com/files/package.json) file.
101+
102+
```console
103+
npm init -y
104+
```
105+
106+
The Azure SDK is composed of many separate packages. You can choose which packages you need based on the services you intend to use. Run following `npm` command in the terminal window to install the `@azure/storage-blob` package.
107+
108+
```console
109+
npm install --save @azure/storage-blob
110+
```
111+
112+
#### Bundle the Azure Blob storage client library
113+
114+
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. Bundling takes JavaScript code written using [Node.js](https://nodejs.org) conventions and converts it into a format that's understood by browsers. This quickstart article uses the [Parcel](https://parceljs.org/) bundler.
115+
116+
Install Parcel by running the following `npm` command in the terminal window:
117+
118+
```console
119+
npm install -g parcel-bundler
120+
```
121+
122+
In Visual Studio Code, open the *package.json* file and add a `browserlist` between the `license` and `dependencies` entries. This `browserlist` targets the latest version of three popular browsers. The full *package.json* file should now look like this:
123+
124+
:::code language="json" source="~/azure-storage-snippets/blobs/quickstarts/JavaScript/V12/azure-blobs-js-browser/package.json" highlight="12-16":::
125+
126+
Save the *package.json* file.
127+
128+
### Import the Azure Blob storage client library
129+
130+
To use Azure SDK libraries inside JavaScript, import the `@azure/storage-blob` package. Create a new file in Visual Studio Code containing the following JavaScript code.
131+
132+
:::code language="javascript" source="~/azure-storage-snippets/blobs/quickstarts/JavaScript/V12/azure-blobs-js-browser/index.js" id="snippet_ImportLibrary":::
133+
134+
Save the file as *index.js* in the *azure-blobs-js-browser* directory.
135+
136+
### Implement the HTML page
137+
138+
Create a new file in Visual Studio Code and add the following HTML code.
139+
140+
:::code language="html" source="~/azure-storage-snippets/blobs/quickstarts/JavaScript/V12/azure-blobs-js-browser/index.html":::
141+
142+
Save the file as *index.html* in the *azure-blobs-js-browser* folder.
143+
144+
## Code examples
145+
146+
The example code shows you how to accomplish the following tasks with the Azure Blob storage client library for JavaScript:
147+
148+
* [Declare fields for UI elements](#declare-fields-for-ui-elements)
149+
* [Add your storage account info](#add-your-storage-account-info)
150+
* [Create client objects](#create-client-objects)
151+
* [Create and delete a storage container](#create-and-delete-a-storage-container)
152+
* [List blobs](#list-blobs)
153+
* [Upload blobs](#upload-blobs)
154+
* [Delete blobs](#delete-blobs)
155+
156+
You'll run the code after you add all the snippets to the *index.js* file.
157+
158+
### Declare fields for UI elements
159+
160+
Add the following code to the end of the *index.js* file.
161+
162+
:::code language="JavaScript" source="~/azure-storage-snippets/blobs/quickstarts/JavaScript/V12/azure-blobs-js-browser/index.js" id="snippet_DeclareVariables":::
163+
164+
Save the *index.js* file.
165+
166+
This code declares fields for each HTML element and implements a `reportStatus` function to display output.
167+
168+
In the following sections, add each new block of JavaScript code after the previous block.
169+
170+
### Add your storage account info
171+
172+
Add code 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 the *index.js* file.
173+
174+
:::code language="javascript" source="~/azure-storage-snippets/blobs/quickstarts/JavaScript/V12/azure-blobs-js-browser/index.js" id="snippet_StorageAcctInfo":::
175+
176+
Save the *index.js* file.
177+
178+
### Create client objects
179+
180+
Create [BlobServiceClient](/javascript/api/@azure/storage-blob/blobserviceclient) and [ContainerClient](/javascript/api/@azure/storage-blob/containerclient) objects for interacting with the Azure Blob storage service. Add the following code to the end of the *index.js* file.
181+
182+
:::code language="javascript" source="~/azure-storage-snippets/blobs/quickstarts/JavaScript/V12/azure-blobs-js-browser/index.js" id="snippet_CreateClientObjects":::
183+
184+
Save the *index.js* file.
185+
186+
### Create and delete a storage container
187+
188+
Create and delete the storage container when you click the corresponding button on the web page. Add the following code to the end of the *index.js* file.
189+
190+
:::code language="javascript" source="~/azure-storage-snippets/blobs/quickstarts/JavaScript/V12/azure-blobs-js-browser/index.js" id="snippet_CreateDeleteContainer":::
191+
192+
Save the *index.js* file.
193+
194+
### List blobs
195+
196+
List the contents of the storage container when you click the **List files** button. Add the following code to the end of the *index.js* file.
197+
198+
:::code language="javascript" source="~/azure-storage-snippets/blobs/quickstarts/JavaScript/V12/azure-blobs-js-browser/index.js" id="snippet_ListBlobs":::
199+
200+
Save the *index.js* file.
201+
202+
This code calls the [ContainerClient.listBlobsFlat](/javascript/api/@azure/storage-blob/containerclient#listblobsflat-containerlistblobsoptions-) function, then uses an iterator to retrieve the name of each [BlobItem](/javascript/api/@azure/storage-blob/blobitem) returned. For each `BlobItem`, it updates the **Files** list with the [name](/javascript/api/@azure/storage-blob/blobitem#name) property value.
203+
204+
### Upload blobs
205+
206+
Upload files to the storage container when you click the **Select and upload files** button. Add the following code to the end of the *index.js* file.
207+
208+
:::code language="javascript" source="~/azure-storage-snippets/blobs/quickstarts/JavaScript/V12/azure-blobs-js-browser/index.js" id="snippet_UploadBlobs":::
209+
210+
Save the *index.js* file.
211+
212+
This code connects the **Select and upload files** button to the hidden `file-input` element. The button `click` event triggers the file input `click` event and displays the file picker. After you select files and close the dialog box, the `input` event occurs and the `uploadFiles` function is called. This function creates a [BlockBlobClient](/javascript/api/@azure/storage-blob/blockblobclient) object, then calls the browser-only [uploadBrowserData](/javascript/api/@azure/storage-blob/blockblobclient#uploadbrowserdata-blob---arraybuffer---arraybufferview--blockblobparalleluploadoptions-) function for each file you selected. Each call returns a `Promise`. Each `Promise` is added to a list so that they can all be awaited together, causing the files to upload in parallel.
213+
214+
### Delete blobs
215+
216+
Delete files from the storage container when you click the **Delete selected files** button. Add the following code to the end of the *index.js* file.
217+
218+
:::code language="javascript" source="~/azure-storage-snippets/blobs/quickstarts/JavaScript/V12/azure-blobs-js-browser/index.js" id="snippet_DeleteBlobs":::
219+
220+
Save the *index.js* file.
221+
222+
This code calls the [ContainerClient.deleteBlob](/javascript/api/@azure/storage-blob/containerclient#deleteblob-string--blobdeleteoptions-) function to remove each file selected in the list. It then calls the `listFiles` function shown earlier to refresh the contents of the **Files** list.
223+
224+
## Run the code
225+
226+
To run the code inside the Visual Studio Code debugger, configure the *launch.json* file for your browser.
227+
228+
### Configure the debugger
229+
230+
To set up the debugger extension in Visual Studio Code:
231+
232+
1. Select **Run > Add Configuration**
233+
2. Select **Edge**, **Chrome**, or **Firefox**, depending on which extension you installed in the [Prerequisites](#prerequisites) section earlier.
234+
235+
Adding a new configuration creates a *launch.json* file and opens it in the editor. Modify the *launch.json* file so that the `url` value is `http://localhost:1234/index.html`, as shown here:
236+
237+
:::code language="json" source="~/azure-storage-snippets/blobs/quickstarts/JavaScript/V12/azure-blobs-js-browser/.vscode/launch.json" highlight="11":::
238+
239+
After updating, save the *launch.json* file. This configuration tells Visual Studio Code which browser to open and which URL to load.
240+
241+
### Launch the web server
242+
243+
To launch the local development web server, select **View > Terminal** to open a console window inside Visual Studio Code, then enter the following command.
244+
245+
```console
246+
parcel index.html
247+
```
248+
249+
Parcel bundles your code and starts a local development server for your page at `http://localhost:1234/index.html`. Changes you make to *index.js* will automatically be built and reflected on the development server whenever you save the file.
250+
251+
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`. In the *launch.json* file, update the port in the URL path to match.
252+
253+
### Start debugging
254+
255+
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.
256+
257+
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.
258+
259+
### Use the web app
260+
261+
In the [Azure portal](https://portal.azure.com), you can verify the results of the API calls as you follow the steps below.
262+
263+
#### Step 1 - Create a container
264+
265+
1. In the web app, select **Create container**. The status indicates that a container was created.
266+
2. To verify in the Azure portal, select your storage account. Under **Blob service**, select **Containers**. Verify that the new container appears. (You may need to select **Refresh**.)
267+
268+
#### Step 2 - Upload a blob to the container
269+
270+
1. On your local computer, create and save a test file, such as *test.txt*.
271+
2. In the web app, click **Select and upload files**.
272+
3. Browse to your test file, and then select **Open**. The status indicates that the file was uploaded, and the file list was retrieved.
273+
4. In the Azure portal, select the name of the new container that you created earlier. Verify that the test file appears.
274+
275+
#### Step 3 - Delete the blob
276+
277+
1. In the web app, under **Files**, select the test file.
278+
2. Select **Delete selected files**. The status indicates that the file was deleted and that the container contains no files.
279+
3. In the Azure portal, select **Refresh**. Verify that you see **No blobs found**.
280+
281+
#### Step 4 - Delete the container
282+
283+
1. In the web app, select **Delete container**. The status indicates that the container was deleted.
284+
2. In the Azure portal, select the **\<account-name\> | Containers** link at the top-left of the portal pane.
285+
3. Select **Refresh**. The new container disappears.
286+
4. Close the web app.
287+
288+
### Clean up resources
289+
290+
Click on the **Terminal** console in Visual Studio Code and press CTRL+C to stop the web server.
291+
292+
To clean up the resources created during this quickstart, go to the [Azure portal](https://portal.azure.com) and delete the resource group you created in the [Prerequisites](#prerequisites) section.
293+
294+
## Next steps
295+
296+
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.
297+
298+
For tutorials, samples, quickstarts, and other documentation, visit:
299+
300+
> [!div class="nextstepaction"]
301+
> [Azure for JavaScript documentation](/azure/javascript/)
302+
303+
* To learn more, see the [Azure Blob storage client library for JavaScript](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/storage/storage-blob).
304+
* To see Blob storage sample apps, continue to [Azure Blob storage client library v12 JavaScript samples](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/storage/storage-blob/samples).

0 commit comments

Comments
 (0)