Upload a file to an Azure Blob Storage

This tutorial shows you how to upload and read from container blobs in an Azure Blob Storage account from a Spring Boot application.

Azure Blob Storage is Microsoft's object storage solution for the cloud. Blob storage is optimized for storing a massive amount of unstructured data, such as text or binary data.

Prerequisites

Note

To grant your account access to resources, in your newly created Azure Storage account, assign the Storage Blob Data Contributor role to the Microsoft Entra account you're currently using. For more information, see Assign Azure roles using the Azure portal.

Important

Spring Boot version 2.5 or higher is required to complete the steps in this tutorial.

Create a container

First, create a container named testcontainer by following the instructions in Quickstart: Upload, download, and list blobs with the Azure portal.

Upload and read blobs from Azure Storage account container

Now that you have an Azure Storage account and container, you can upload and read files from blobs with Spring Cloud Azure.

To install the Spring Cloud Azure Storage Blob Starter module, add the following dependencies to your pom.xml file:

  • The Spring Cloud Azure Bill of Materials (BOM):

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.azure.spring</groupId>
          <artifactId>spring-cloud-azure-dependencies</artifactId>
          <version>5.13.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    

    Note

    If you're using Spring Boot 2.x, be sure to set the spring-cloud-azure-dependencies version to 4.19.0. This Bill of Material (BOM) should be configured in the <dependencyManagement> section of your pom.xml file. This ensures that all Spring Cloud Azure dependencies are using the same version. For more information about the version used for this BOM, see Which Version of Spring Cloud Azure Should I Use.

  • The Spring Cloud Azure Storage Blob Starter artifact:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-storage-blob</artifactId>
    </dependency>
    

Code the application

To upload and read files from blobs by using the Spring Cloud Azure Storage Blob starter, configure the application by using the following steps.

  1. Configure a Storage account name and endpoint in the application.properties configuration file, as shown in the following example.

    spring.cloud.azure.storage.blob.account-name=${AZURE_STORAGE_ACCOUNT_NAME}
    spring.cloud.azure.storage.blob.endpoint=${AZURE_STORAGE_ACCOUNT_ENDPOINT}
    
  2. Create a new BlobController Java class as shown in the following example. This class is used to upload and read files from the container blob in the Azure Storage account.

    package com.example.demo;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.io.Resource;
    import org.springframework.core.io.WritableResource;
    import org.springframework.util.StreamUtils;
    import org.springframework.web.bind.annotation.*;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.nio.charset.Charset;
    
    @RestController
    @RequestMapping("blob")
    public class BlobController {
    
        @Value("azure-blob://testcontainer/test.txt")
        private Resource blobFile;
    
        @GetMapping("/readBlobFile")
        public String readBlobFile() throws IOException {
            return StreamUtils.copyToString(
                    this.blobFile.getInputStream(),
                    Charset.defaultCharset());
        }
    
        @PostMapping("/writeBlobFile")
        public String writeBlobFile(@RequestBody String data) throws IOException {
            try (OutputStream os = ((WritableResource) this.blobFile).getOutputStream()) {
                os.write(data.getBytes());
            }
            return "file was updated";
        }
    }
    

    Tip

    In this tutorial, there are no authentication operations in the configurations or the code. However, connecting to Azure services requires authentication. To complete the authentication, you need to use Azure Identity. Spring Cloud Azure uses DefaultAzureCredential, which the Azure Identity library provides to help you get credentials without any code changes.

    DefaultAzureCredential supports multiple authentication methods and determines which method to use at runtime. This approach enables your app to use different authentication methods in different environments (such as local and production environments) without implementing environment-specific code. For more information, see DefaultAzureCredential.

    To complete the authentication in local development environments, you can use Azure CLI, Visual Studio Code, PowerShell, or other methods. For more information, see Azure authentication in Java development environments. To complete the authentication in Azure hosting environments, we recommend using user-assigned managed identity. For more information, see What are managed identities for Azure resources?

  3. After your application is running, use curl to test your application by following these steps.

    1. Send a POST request to update a file's contents by using the following command:

      curl http://localhost:8080/blob/writeBlobFile -d "new message" -H "Content-Type: text/plain"
      

      You should see a response that says file was updated.

    2. Send a GET request to verify the file's contents by using the following command:

      curl -X GET http://localhost:8080/blob/readBlobFile
      

      You should see the "new message" text that you posted.

Deploy to Azure Spring Apps

Now that you have the Spring Boot application running locally, it's time to move it to production. Azure Spring Apps makes it easy to deploy Spring Boot applications to Azure without any code changes. The service manages the infrastructure of Spring applications so developers can focus on their code. Azure Spring Apps provides lifecycle management using comprehensive monitoring and diagnostics, configuration management, service discovery, CI/CD integration, blue-green deployments, and more. To deploy your application to Azure Spring Apps, see Deploy your first application to Azure Spring Apps.

Next steps

To learn more about Spring and Azure, continue to the Spring on Azure documentation center.

See also

For more information about the additional Spring Boot Starters that are available for Microsoft Azure, see What is Spring Cloud Azure?

For more information about additional Azure storage APIs that you can call from your Spring Boot applications, see the following articles: