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

Upload a block blob with Java

Feedback

In this article

This article shows how to upload a block blob using theAzure Storage client library for Java. You can upload data to a block blob from a file path, a stream, a binary object, or a text string. You can also upload blobs with index tags.

Prerequisites

Set up your environment

If you don't have an existing project, this section shows you how to set up a project to work with the Azure Blob Storage client library for Java. For more information, seeGet started with Azure Blob Storage and Java.

To work with the code examples in this article, follow these steps to set up your project.

Note

This article uses the Maven build tool to build and run the example code. Other build tools, such as Gradle, also work with the Azure SDK for Java.

Install packages

Open thepom.xml file in your text editor. Install the packages byincluding the BOM file, orincluding a direct dependency.

Add import statements

Add the followingimport statements:

import com.azure.core.http.rest.*;import com.azure.core.util.BinaryData;import com.azure.storage.blob.*;import com.azure.storage.blob.models.*;import com.azure.storage.blob.options.BlobUploadFromFileOptions;import com.azure.storage.blob.specialized.*;import java.io.ByteArrayInputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.UncheckedIOException;import java.nio.charset.StandardCharsets;import java.nio.file.Path;import java.time.Duration;import java.util.*;

Authorization

The authorization mechanism must have the necessary permissions to upload a blob. For authorization with Microsoft Entra ID (recommended), you need Azure RBAC built-in roleStorage Blob Data Contributor or higher. To learn more, see the authorization guidance forPut Blob (REST API) andPut Block (REST API).

Create a client object

To connect an app to Blob Storage, create an instance ofBlobServiceClient.

The following example usesBlobServiceClientBuilder to build aBlobServiceClient object usingDefaultAzureCredential, and shows how to create container and blob clients, if needed:

// Azure SDK client builders accept the credential as a parameter// TODO: Replace <storage-account-name> with your actual storage account nameBlobServiceClient blobServiceClient = new BlobServiceClientBuilder()        .endpoint("https://<storage-account-name>.blob.core.windows.net/")        .credential(new DefaultAzureCredentialBuilder().build())        .buildClient();// If needed, you can create a BlobContainerClient object from the BlobServiceClientBlobContainerClient containerClient = blobServiceClient        .getBlobContainerClient("<container-name>");// If needed, you can create a BlobClient object from the BlobContainerClientBlobClient blobClient = containerClient        .getBlobClient("<blob-name>");

To learn more about creating and managing client objects, seeCreate and manage client objects that interact with data resources.

Upload data to a block blob

To upload a block blob from a stream or a binary object, use the following method:

To upload a block blob from a file path, use the following method:

Each of these methods can be called using aBlobClient object or aBlockBlobClient object.

Note

The Azure Storage client libraries don't support concurrent writes to the same blob. If your app requires multiple processes writing to the same blob, you should implement a strategy for concurrency control to provide a predictable experience. To learn more about concurrency strategies, seeManage concurrency in Blob Storage.

Upload a block blob from a local file path

The following example uploads a file to a block blob using aBlobClient object:

public void uploadBlobFromFile(BlobContainerClient blobContainerClient) {    BlobClient blobClient = blobContainerClient.getBlobClient("sampleBlob.txt");    try {        blobClient.uploadFromFile("filepath/local-file.png");    } catch (UncheckedIOException ex) {        System.err.printf("Failed to upload from file: %s%n", ex.getMessage());    }}

Upload a block blob from a stream

The following example uploads a block blob by creating aByteArrayInputStream object, then uploading that stream object:

public void uploadBlobFromStream(BlobContainerClient blobContainerClient) {    BlockBlobClient blockBlobClient = blobContainerClient.getBlobClient("sampleBlob.txt").getBlockBlobClient();    String sampleData = "Sample data for blob";    try (ByteArrayInputStream dataStream = new ByteArrayInputStream(sampleData.getBytes())) {        blockBlobClient.upload(dataStream, sampleData.length());    } catch (IOException ex) {        ex.printStackTrace();    }}

Upload a block blob from a BinaryData object

The following example uploadsBinaryData to a block blob using aBlobClient object:

public void uploadDataToBlob(BlobContainerClient blobContainerClient) {    // Create a BlobClient object from BlobContainerClient    BlobClient blobClient = blobContainerClient.getBlobClient("sampleBlob.txt");    String sampleData = "Sample data for blob";    blobClient.upload(BinaryData.fromString(sampleData));}

Upload a block blob with configuration options

You can define client library configuration options when uploading a blob. These options can be tuned to improve performance, enhance reliability, and optimize costs. The following code examples show how to useBlobUploadFromFileOptions to define configuration options when calling an upload method. If you're not uploading from a file, you can set similar options usingBlobParallelUploadOptions on an upload method.

Specify data transfer options on upload

You can configure values inParallelTransferOptions to improve performance for data transfer operations. The following values can be tuned for uploads based on the needs of your app:

  • blockSize: The maximum block size to transfer for each request. You can set this value by using thesetBlockSizeLong method.
  • maxSingleUploadSize: If the size of the data is less than or equal to this value, it's uploaded in a single put rather than broken up into chunks. If the data is uploaded in a single shot, the block size is ignored. You can set this value by using thesetMaxSingleUploadSizeLong method.
  • maxConcurrency: The maximum number of parallel requests issued at any given time as a part of a single parallel transfer. You can set this value by using thesetMaxConcurrency method.

Make sure you have the followingimport directive to useParallelTransferOptions for an upload:

import com.azure.storage.blob.models.*;

The following code example shows how to set values forParallelTransferOptions and include the options as part of aBlobUploadFromFileOptions instance. The values provided in this sample aren't intended to be a recommendation. To properly tune these values, you need to consider the specific needs of your app.

public void uploadBlockBlobWithTransferOptions(BlobContainerClient blobContainerClient, Path filePath) {    String fileName = filePath.getFileName().toString();    BlobClient blobClient = blobContainerClient.getBlobClient(fileName);    ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions()            .setBlockSizeLong((long) (4 * 1024 * 1024)) // 4 MiB block size            .setMaxConcurrency(2)            .setMaxSingleUploadSizeLong((long) 8 * 1024 * 1024); // 8 MiB max size for single request upload    BlobUploadFromFileOptions options = new BlobUploadFromFileOptions(filePath.toString());    options.setParallelTransferOptions(parallelTransferOptions);    try {        Response<BlockBlobItem> blockBlob = blobClient.uploadFromFileWithResponse(options, null, null);    } catch (UncheckedIOException ex) {        System.err.printf("Failed to upload from file: %s%n", ex.getMessage());    }}

To learn more about tuning data transfer options, seePerformance tuning for uploads and downloads with Java.

Upload a block blob with index tags

Blob index tags categorize data in your storage account using key-value tag attributes. These tags are automatically indexed and exposed as a searchable multi-dimensional index to easily find data.

The following example uploads a block blob with index tags set usingBlobUploadFromFileOptions:

public void uploadBlockBlobWithIndexTags(BlobContainerClient blobContainerClient, Path filePath) {    String fileName = filePath.getFileName().toString();    BlobClient blobClient = blobContainerClient.getBlobClient(fileName);    Map<String, String> tags = new HashMap<String, String>();    tags.put("Content", "image");    tags.put("Date", "2022-01-01");    Duration timeout = Duration.ofSeconds(10);    BlobUploadFromFileOptions options = new BlobUploadFromFileOptions(filePath.toString());    options.setTags(tags);    try {        // Create a new block blob, or update the content of an existing blob        Response<BlockBlobItem> blockBlob = blobClient.uploadFromFileWithResponse(options, timeout, null);    } catch (UncheckedIOException ex) {        System.err.printf("Failed to upload from file: %s%n", ex.getMessage());    }}

Set a blob's access tier on upload

You can set a blob's access tier on upload by using theBlobUploadFromFileOptions class. The following code example shows how to set the access tier when uploading a blob:

public void uploadBlobWithAccessTier(BlobContainerClient blobContainerClient, Path filePath) {    String fileName = filePath.getFileName().toString();    BlobClient blobClient = blobContainerClient.getBlobClient(fileName);    BlobUploadFromFileOptions options = new BlobUploadFromFileOptions(filePath.toString())            .setTier(AccessTier.COOL);    try {        Response<BlockBlobItem> blockBlob = blobClient.uploadFromFileWithResponse(options, null, null);    } catch (UncheckedIOException ex) {        System.err.printf("Failed to upload from file: %s%n", ex.getMessage());    }}

Setting the access tier is only allowed for block blobs. You can set the access tier for a block blob toHot,Cool,Cold, orArchive. To set the access tier toCold, you must use a minimumclient library version of 12.21.0.

To learn more about access tiers, seeAccess tiers overview.

Upload a block blob by staging blocks and committing

You can have greater control over how to divide uploads into blocks by manually staging individual blocks of data. When all of the blocks that make up a blob are staged, you can commit them to Blob Storage. You can use this approach to enhance performance by uploading blocks in parallel.

public void uploadBlocks(BlobContainerClient blobContainerClient, Path filePath, int blockSize) throws IOException {    String fileName = filePath.getFileName().toString();    BlockBlobClient blobClient = blobContainerClient.getBlobClient(fileName).getBlockBlobClient();    FileInputStream fileStream = new FileInputStream(filePath.toString());    List<String> blockIDArrayList = new ArrayList<>();    byte[] buffer = new byte[blockSize];    int bytesRead;    while ((bytesRead = fileStream.read(buffer, 0, blockSize)) != -1) {        try (ByteArrayInputStream stream = new ByteArrayInputStream(buffer)) {            String blockID = Base64.getEncoder().encodeToString(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));            blockIDArrayList.add(blockID);            blobClient.stageBlock(blockID, stream, buffer.length);        }    }    blobClient.commitBlockList(blockIDArrayList);    fileStream.close();}

Resources

To learn more about uploading blobs using the Azure Blob Storage client library for Java, see the following resources.

Code samples

REST API operations

The Azure SDK for Java contains libraries that build on top of the Azure REST API, allowing you to interact with REST API operations through familiar Java paradigms. The client library methods for uploading blobs use the following REST API operations:

Client library resources

See also

Related content

  • This article is part of the Blob Storage developer guide for Java. To learn more, see the full list of developer guide articles atBuild your Java app.

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?