Skip to content Skip to sidebar Skip to footer

How Upload Files Direct to an Storage in Azure Blob Storage Example

Skip to main content

Upload an prototype to an Azure Storage blob

Use a client-side React app to upload an prototype file to an Azure Storage blob using an Azure Storage @azure/storage-hulk npm package.

The TypeScript programming work is done for yous, this tutorial focuses on using the local and remote Azure environments successfully from inside Visual Studio Code with Azure extensions.

  • Sample lawmaking
  • Azure Blob Storage reference documentation

Application architecture and functionality

This commodity includes several superlative Azure tasks for JavaScript developers:

  • Run a React/TypeScript app locally with Visual Studio Code
  • Create an Azure Storage Hulk resources and configure for file uploads
    • Configure CORS
    • Create Shared admission signatures (SAS) token
  • Configure code for Azure SDK client library to apply SAS token to authenticate to service

The sample React app, available on GitHub, consists of the post-obit elements:

  • React app hosted on port 3000
  • Azure SDK client library script to upload to Storage blobs

Simple React app connected to Azure Storage blobs.

1. Prepare development environment

  • An Azure user account with an active subscription. Create ane for gratuitous.
  • Node.js LTS with NPM, the Node.js package manager installed to your local car.
  • Visual Studio Code installed to your local motorcar.
  • Visual Studio Code extensions:
    • Azure Resources
    • Azure Storage - used to view Storage resources
    • Azure Static Web Apps - used to create and deploy the React app to Azure

2. Fork and clone the sample application

  1. Open this GitHub sample URL in a web browser:

                      https://github.com/Azure-Samples/js-e2e-browser-file-upload-storage-blob                                  
  2. Select Fork to create your own fork of this sample project. Your own GitHub fork is necessary to deploy this sample to Azure as a static web app.

  3. Select the Lawmaking push button, and then copy the Clone URL.

  4. In a fustigate last, clone your forked repository, replacing REPLACE-WITH-YOUR-ACCOUNT-Proper noun with your GitHub account proper name:

                      git clone https://github.com/Supplant-WITH-YOUR-Account-NAME/js-e2e-browser-file-upload-storage-hulk                                  
  5. Change into the new directory and open Visual Studio Code.

                      cd js-e2e-browser-file-upload-storage-hulk && code .                                  

3. Install dependencies and run local projection

  1. In Visual Studio Code, open an integrated fustigate last, Ctrl + Shift + `, and run the post-obit command to install the sample'southward dependencies.

                      npm install                                  
  2. In the same terminal window, run the command to run the web app.

                      npm offset                                  
  3. Open a spider web browser and use the following url to view the web app on your local computer.

                      http://localhost:3000/                                  

    If you see the simple web app in your browser with the text that the Storage isn't configured, you have succeeded with this section of the tutorial.

    Simple Node.js app connected to MongoDB database.

  4. Stop the lawmaking with Ctrl + C in the Visual Studio Code final.

4. Create Storage resource with Visual Studio extension

  1. Navigate to the Azure Storage extension. Right-click on the subscription then select Create Storage Business relationship....

    Navigate to the Azure Storage extension. Right-click on the subscription then select `Create Storage Account...`.

  2. Follow the prompts using the following table to sympathise how to create your Storage resource.

    Property Value
    Enter a globally unique proper noun for the new spider web app. Enter a value such as fileuploaddemo, for your Storage resources name.

    This unique name is your resource name used in the next section. Use only characters and numbers, up to 24 in length. You need this account name to use subsequently.

  3. When the app creation process is consummate, a notification appears with information about the new resource.

    When the app creation process is complete, a notification appears with information about the new resource.

Generate the SAS token before configuring CORS.

  1. In the Visual Studio Code extension for Storage, correct-click the resource then select Open in Portal. This opens the Azure portal to your exact Storage resource.

  2. In the Security + networking section, select Shared admission signature.

  3. Configure the SAS token with the following settings.

    Property Value
    Allowed services Blob
    Allowed resource types Service, Container, Object
    Allowed permissions Read, write, delete, list, add together, create
    Hulk versioning permissions Checked
    Allow blob alphabetize permissions Read/Write and Filter should be checked
    Start and decease date/fourth dimension Accept the get-go appointment/time and prepare the cease date time 24 hours in the future. Your SAS token is only good for 24 hours.
    HTTPS only Selected
    Preferred routing tier Basic
    Signing Primal key1 selected

    Configure the SAS token as show in the image. The settings are explained below the image.

  4. Select Generate SAS and connection cord.

  5. Immediately copy the SAS token. Y'all won't be able to listing this token so if you don't accept it copied, y'all will need to generate a new SAS token.

half-dozen. Set up Storage values in .env file

The SAS token is used when queries are made to your cloud-based resource.

  1. Create a file name .env at the root of the project.

  2. Add together two required variables with their storage values:

                      REACT_APP_STORAGESASTOKEN= REACT_APP_STORAGERESOURCENAME=                                  

    React builds the static files with these variables.

  3. If the token begins with a question mark, remove the ?. The code file provides the ? for you and so you don't need it in the token.

7. Configure CORS for Azure Storage resource

Configure CORS for your resource so the customer-side React lawmaking can access your storage account.

  1. While even so in the Azure portals, in the Settings section, select Resources sharing (CORS).

  2. Configure the Hulk service CORS equally show in the image. The settings are explained below the epitome.

    Property Value
    Allowed origins *
    Allowed methods All except patch.
    Allowed headers *
    Exposed headers *
    Max historic period 86400

    Configure CORS as show in the image. The settings are explained below the image.

  3. Select Save above the settings to relieve them to the resource. The code doesn't require any changes to work with these CORS settings.

8. Run project locally to verify connection to Storage account

Your SAS token and storage account proper noun are set in the src/azure-storage-blob.ts file, so you are prepare to run the application.

  1. If the app isn't running, kickoff it again:

                      npm kickoff                                  
  2. Open the following URL in a browser:

    http://localhost:3000

    The React website connected to Azure Storage blobs should display with a file selection button and a file upload button.

  3. Select an image from the images folder to upload then select the Upload! button.

  4. The React forepart-end client code calls into the ./src/azure-storage-blob.ts to authenticate to Azure, and then create a Storage Container (if it doesn't already exist), then uploads the file to that container.

9. Deploy static web app to Azure

  1. In Visual Studio Code, select the Azure explorer.

  2. If you see a pop-upwardly window asking you to commit your changes, don't practice this. The sample should be set up to deploy without changes.

    To roll back the changes, in Visual Studio Code, select the Source Control icon in the activity bar. And then select each changed file in the Changes list, and select the Discard changes icon.

  3. Right-click on the subscription name, then select Create Static Web App (Advanced).

  4. Follow the prompts to provide the following data:

    Prompt Enter
    Enter the name for the new static web app. Create a unique proper noun for your resources. For example, you can prepend your proper name to the repository proper name, such as upload-file-to-storage.
    Select a resources group for new resources. Use the resources group that y'all created for your storage resources.
    Select a SKU Select the gratuitous SKU for this tutorial. If you already accept a free Static Web App resource used, select the next pricing tier.
    Choose build preset to configure default project construction. Select React.
    Select the location of your application code / - This indicates the packet.json file is at the root of the repository.
    Select the location of your Azure Functions code Accept the default value. While this sample doesn't use an API, you can add one later.
    Enter the path of your build output... build

    This is the path from your app to your static (generated) files.

    Select a location for new resources. Select a region close to yous.
  5. When the process is consummate, a notification pop-upward displays. Select View/Edit Workflow.

    Partial screenshot of Visual Studio Code notification pop-up with View/Edit Workflow button highlighted.

10. Add together Azure Storage secrets to GitHub secrets

  1. In a web browser, render to your GitHub fork of the sample projection to add the 2 secrets and their values:

                      https://github.com/YOUR-GITHUB-Business relationship/js-e2e-browser-file-upload-storage-blob/settings/secrets/actions                                  

    Screenshot of a web browser displaying https://github.com, on the Settings -> Secrets page, with the New repository secret button highlighted.

11. Configure static web app to connect to storage resource

Edit the GitHub workflow and secrets to connect to Azure Storage.

  1. In Visual Studio Lawmaking, open the .github/workflows workflow YAML file and add the 2 storage environs variables after the with department to the build_and_deploy_job.

                      jobs:   build_and_deploy_job:     if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.effect.activeness != 'airtight')     runs-on: ubuntu-latest     name: Build and Deploy Job     steps:       - uses: actions/checkout@v2         with:           submodules: true       - name: Build And Deploy         id: builddeploy         uses: Azure/static-web-apps-deploy@v1         with:           azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_123456 }}           repo_token: ${{ secrets.GITHUB_TOKEN }} # Used for Github integrations (i.eastward. PR comments)           action: "upload"           ###### Repository/Build Configurations - These values can exist configured to match your app requirements. ######           # For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig           app_location: "/" # App source code path           api_location: "api" # Api source lawmaking path - optional           output_location: "build" # Built app content directory - optional           ###### Stop of Repository/Build Configurations ######         env: # Add environment variables here             REACT_APP_STORAGESASTOKEN: ${{secrets.REACT_APP_STORAGESASTOKEN}}             REACT_APP_STORAGERESOURCENAME: ${{secrets.REACT_APP_STORAGERESOURCENAME}}                                  

    This pulls in the secrets to the build process.

  2. In Visual Studio Code, select Source Control, Ctrl + Shift + G, then select the addition icon to add the inverse *.yml file.

  3. Enter a annotate for your commit such as Adding Storage secrets.

  4. Button to your GitHub fork by selecting the Synchronize changes icon on the status bar.

    Partial screenshot of Visual Studio Code status bar.

  5. In the pop-up window to confirm if you want to push and pull from your remote repository, select OK.

    If you go an fault at this step, checkout your git remote to make sure you cloned your fork: git remote -v.

  6. This push triggers a new build and deploy for your static web app.

12. Verify build and deploy job completes

  1. In a web browser, return to your GitHub fork of the sample project.

  2. Select Deportment, then select the Azure Static Web Apps CI/CD activeness.

  3. Select the Build and Deploy Job to watch the process complete.

    Screenshot of web browser showing GitHub action success

13. Use the Azure-deployed static web app

  1. In Visual Studio Code, right-click your Static web app from the Azure explorer and select

    Partial screenshot selecting Browse Site from the Azure Static web site.

  2. In the new web browser window, choose a file and upload the file.

Troubleshoot local connection to Storage account

If yous received an error or your file doesn't upload to the container, check the post-obit:

  • Recreate your SAS token, making sure that your token is created at the Storage resources level and not the container level. Copy the new token into the code at the right location.
  • Check that the token string you lot copied into the lawmaking doesn't contain the ? (question marking) at the beginning of the string.
  • Verify your CORS setting for your Storage resource.

Upload button functionality

The src/App.tsx TypeScript file is provided as part of that app cosmos with create-react-app. The file has been modified to provide the file selection button and the upload button and the supporting lawmaking to provide that functionality.

The code connecting to the Azure Blob Storage lawmaking is highlighted. The call to uploadFileToBlob returns all blobs (files) in the container as a flat list. That listing is displayed with the DisplayImagesFromContainer part.

              // ./src/App.tsx  import React, { useState } from 'react'; import Path from 'path'; import uploadFileToBlob, { isStorageConfigured } from './azure-storage-blob';  const storageConfigured = isStorageConfigured();  const App = (): JSX.Element => {   // all blobs in container   const [blobList, setBlobList] = useState<string[]>([]);    // electric current file to upload into container   const [fileSelected, setFileSelected] = useState(null);    // UI/class management   const [uploading, setUploading] = useState(false);   const [inputKey, setInputKey] = useState(Math.random().toString(36));    const onFileChange = (event: whatsoever) => {     // capture file into land     setFileSelected(issue.target.files[0]);   };    const onFileUpload = async () => {     // prepare UI     setUploading(truthful);      // *** UPLOAD TO AZURE STORAGE ***     const blobsInContainer: string[] = await uploadFileToBlob(fileSelected);      // gear up UI for results     setBlobList(blobsInContainer);      // reset state/form     setFileSelected(cipher);     setUploading(false);     setInputKey(Math.random().toString(36));   };    // brandish form   const DisplayForm = () => (     <div>       <input type="file" onChange={onFileChange} primal={inputKey || ''} />       <button type="submit" onClick={onFileUpload}>         Upload!           </button>     </div>   )    // display file name and image   const DisplayImagesFromContainer = () => (     <div>       <h2>Container items</h2>       <ul>         {blobList.map((item) => {           return (             <li key={item}>               <div>                 {Path.basename(item)}                 <br />                 <img src={item} alt={detail} peak="200" />               </div>             </li>           );         })}       </ul>     </div>   );    return (     <div>       <h1>Upload file to Azure Blob Storage</h1>       {storageConfigured && !uploading && DisplayForm()}       {storageConfigured && uploading && <div>Uploading</div>}       <hr />       {storageConfigured && blobList.length > 0 && DisplayImagesFromContainer()}       {!storageConfigured && <div>Storage is not configured.</div>}     </div>   ); };  export default App;                          

Upload file to Azure Storage hulk with Azure SDK client library

The code to upload the file to the Azure Storage is framework-agnostic. Equally the lawmaking is built for a tutorial, choices were made for simplicity and comprehension. These choices are explained; you lot should review your own project for intentional use, security, and efficiency.

The sample creates and uses a publicly accessible container and files. If you want to secure your files in your own project, you have many layers where you can command that from requiring overall hallmark to your resource to very specific permissions on each hulk object.

Dependencies and variables

The azure-storage-hulk.ts TypeScript file loads the dependencies, and pulls in the required variables by either environment variables or hard-coded strings.

Variable Description
sasToken The SAS token created with the Azure portal is prepended with a ?. Remove it before setting it in your sasToken variable.
container The name of the container in Blob storage. Yous tin can call back of this equally equivalent to a folder or directory for a file organisation.
storageAccountName Your resource name.
              // THIS IS SAMPLE CODE ONLY - Non MEANT FOR Production Employ import { BlobServiceClient, ContainerClient} from '@azure/storage-blob';  const containerName = `tutorial-container`; const sasToken = procedure.env.REACT_APP_STORAGESASTOKEN; const storageAccountName = process.env.REACT_APP_STORAGERESOURCENAME;                          

Create Storage client and manage steps

The uploadFileToBlob role is the chief function of the file. It creates the client object for the Storage service, then creates the client to the container object, uploads the file, then gets a list of all the blobs in the container.

              const uploadFileToBlob = async (file: File | null): Promise<string[]> => {   if (!file) return [];    // get BlobService = notice `?` is pulled out of sasToken - if created in Azure portal   const blobService = new BlobServiceClient(     `https://${storageAccountName}.hulk.core.windows.net/?${sasToken}`   );    // get Container - total public read access   const containerClient: ContainerClient = blobService.getContainerClient(containerName);   wait containerClient.createIfNotExists({     access: 'container',   });    // upload file   look createBlobInContainer(containerClient, file);    // go list of blobs in container   return getBlobsInContainer(containerClient); };                          

Upload file to blob

The createBlobInContainer part uploads the file to the container, using the BlockBlobClient class, uploadData method. The content type must exist sent with the asking if you intend to apply browser functionality, which depends on the file blazon, such as displaying a motion-picture show.

              const createBlobInContainer = async (containerClient: ContainerClient, file: File) => {      // create blobClient for container   const blobClient = containerClient.getBlockBlobClient(file.proper name);    // set up mimetype as adamant from browser with file upload command   const options = { blobHTTPHeaders: { blobContentType: file.type } };    // upload file   await blobClient.uploadData(file, options); }                          

Get listing of blobs

The getBlobsInContainer function gets a list of URLs, using the ContainerClient class, listBlobsFlat method, for the blobs in the container. The URLs are synthetic to be used as the src of an image display in HTML: <img src={item} alt={particular} summit="200" />.

              // render list of blobs in container to display const getBlobsInContainer = async (containerClient: ContainerClient) => {   const returnedBlobUrls: string[] = [];    // get listing of blobs in container   // eslint-disable-next-line   for await (const blob of containerClient.listBlobsFlat()) {     // if image is public, just construct URL     returnedBlobUrls.push button(       `https://${storageAccountName}.blob.core.windows.net/${containerName}/${blob.proper name}`     );   }    render returnedBlobUrls; }                          

Clean up resources

In Visual Studio Code, utilise the Azure explorer for Resource Groups, right-click on the your resources group then select Delete.

This deletes all resources in the group, including your Storage and Static Web app resource.

Next steps

If you would like to continue with this app, learn how to deploy the app to Azure for hosting with ane of the post-obit choices:

  • Upload as a static web app
  • Upload to a web app resources using the Visual Studio code extension for the App service
  • Upload an app to an Azure VM
  • Azure Blob Storage documentation
  • @azure/storage-blob
    • NPM package
    • Reference documentation
  • Azure Static Web app

strangkneand.blogspot.com

Source: https://docs.microsoft.com/en-us/azure/developer/javascript/tutorial/browser-file-upload-azure-storage-blob

Publicar un comentario for "How Upload Files Direct to an Storage in Azure Blob Storage Example"