【Azure 存储服务】Java Storage SDK 调用 uploadWithResponse 代码示例(询问ChatGTP得代码原型后人力验证)

简介: 【Azure 存储服务】Java Storage SDK 调用 uploadWithResponse 代码示例(询问ChatGTP得代码原型后人力验证)

问题描述

查看Java Storage SDK,想找一个 uploadWithResponse  的示例代码,但是通过全网搜索,结果没有任何有帮助的代码。使用最近ChatGPT来寻求答案,得到非常有格式的内容:

问:java azure storage account to use uploadWithResponse

答:To use the uploadWithResponse method with the Azure Blob Storage client library for Java, follow these steps:

  1. Add the Azure Storage Blob dependency to your project's build file. For Maven, add the following to your pom.xml:
<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-storage-blob</artifactId>
  <version>12.14.2</version>
</dependency>
  1. Import the necessary classes:
import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
  1. Create a BlobServiceClient instance using your storage account connection string:
String connectionString = "your_connection_string";
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectionString).buildClient();
  1. Get a reference to the container and the blob you want to upload:
String containerName = "your_container_name";
String blobName = "your_blob_name";
BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerName);
BlobClient blobClient = containerClient.getBlobClient(blobName);
  1. Upload a file using the uploadWithResponse method:
import com.azure.storage.blob.models.BlobUploadFromFileOptions;
import java.nio.file.Path;
import java.nio.file.Paths;

Path filePath = Paths.get("path/to/your/file");
BlobUploadFromFileOptions options = new BlobUploadFromFileOptions(filePath);
blobClient.uploadWithResponse(options, null, null);

 

This will upload the file to the specified blob in the Azure Blob Storage container. Remember to replace the placeholders with your actual connection string, container name, blob name, and file path.

继续追问:BlobParallelUploadOptions with string content

答:(前面4步的答案一样,第五步的内容为)

  1. Convert the string content to an InputStream and set up BlobParallelUploadOptions:
String content = "your_string_content";
InputStream inputStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
long blockSize = 100 * 1024L; // 100 KB
int maxConcurrency = 5;
ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions(blockSize, maxConcurrency);
BlobParallelUploadOptions options = new BlobParallelUploadOptions(inputStream).setParallelTra

在继续问:如何使用 “To avoid overwriting, pass "*" to setIfNoneMatch(String ifNoneMatch). how to use the setifnonematch” 

答:(前面4步的答案一样,第五步的内容为)
  1. Set up BlobUploadOptions with setIfNoneMatch:
BlobUploadOptions options = new BlobUploadOptions()
    .setInputStream(inputStream)
    .setLength((long) content.length())
    .setHttpHeaders(new BlobHttpHeaders().setContentType("text/plain"))
    .setRequestConditions(new BlobRequestConditions().setIfNoneMatch("*"));
  1. Upload the string content using the uploadWithResponse method with BlobUploadOptions:
blobClient.uploadWithResponse(options, null, null);

This will upload the string content to the specified blob in the Azure Blob Storage container only if the blob does not already exist. If the blob exists, the upload will fail with a BlobStorageException due to the setIfNoneMatch("*") condition. Remember to replace the placeholders with your actual connection string, container name, blob name, and string content.

 

问题解答

根据ChatGPT提供的三部分信息,通过人力拼接和测试。得到了成功执行的uploadWithResponse代码:

uploadWithResponse示例代码

String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=***************";
            String containerName = "******************";
            String fileName  = "******************";
                BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
                                .connectionString(storageConnectionString)
                                .buildClient();
                BlobContainerClient containerClient = blobServiceClient.createBlobContainer(containerName);
                BlobClient blobClient = containerClient.getBlobClient(fileName);
                //准备content并且初始化blob parallel upload options对象
               String content = "Test to append new content into exists blob! by blogs lu bian liang zhan deng ";
                InputStream inputStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
                BlobParallelUploadOptions options = new BlobParallelUploadOptions(inputStream, content.getBytes().length);
                options.setRequestConditions(new BlobRequestConditions().setIfNoneMatch("*"));
                Response<BlockBlobItem> rsp = blobClient.uploadWithResponse(options, null, null);
                if(rsp.getStatusCode()==201)
                {
                        System.out.println("append content successful........");                        
                }

说明:

1) content 中为需要写入Blob的内容

2) 把string转换为以UTF_8编码的input stream

3) 根据 input stream来初始化 blob paralle upload options对象

4) 设置 Request Conditions,当不需要重写的时候,可以使用 setIfNoneMatch("*")。如果操作的文件存在,则会出现  Status code 409, BlobAlreadyExistss 提示。

5) 调用upload with response方法,获取返回值,如果 返回值得status code为 201,表示Storage Account接受了这次 blob 内容的改动。

 

运行效果展示图

 

 

参考资料

BlobClient Class:https://learn.microsoft.com/en-us/java/api/com.azure.storage.blob.BlobClient?view=azure-java-stable

BlobRequestConditions Class:https://learn.microsoft.com/en-us/java/api/com.azure.storage.blob.models.blobrequestconditions?view=azure-java-stable#com-azure-storage-blob-models-blobrequestconditions-setifnonematch(java-lang-string)

适用于 Java 的 Azure Blob 存储客户端库 : https://docs.azure.cn/zh-cn/storage/blobs/storage-quickstart-blobs-java?tabs=powershell%2Cmanaged-identity%2Croles-azure-portal%2Csign-in-azure-cli#upload-blobs-to-a-container

相关文章
|
20天前
|
存储 Java 开发工具
【Azure 存储服务】Azure Blob Storage SDK 升级失败,遇见 Unsatisfied Dependency Exception 和 Unexpected Length Exception
【Azure 存储服务】Azure Blob Storage SDK 升级失败,遇见 Unsatisfied Dependency Exception 和 Unexpected Length Exception
|
14天前
|
Java 开发工具
通过Java SDK调用阿里云模型服务
在阿里云平台上,可以通过创建应用并使用模型服务完成特定任务,如生成文章内容。本示例展示了一段简化的Java代码,演示了如何调用阿里云模型服务生成关于“春秋战国经济与文化”的简短文章。示例代码通过设置系统角色为历史学家,并提出文章生成需求,最终处理并输出生成的文章内容。在实际部署前,请确保正确配置环境变量中的密钥和ID,并根据需要调整SDK导入语句及类名。更多详情和示例,请参考相关链接。
|
20天前
|
存储 API 开发工具
【Azure Storage Blob】如何通过.NET Azure Storage Blobs SDK获取到Blob的MD5值呢?
【Azure Storage Blob】如何通过.NET Azure Storage Blobs SDK获取到Blob的MD5值呢?
|
20天前
|
Java 开发工具
【Azure Developer】示例: 在中国区调用MSGraph SDK通过User principal name获取到User信息,如Object ID
【Azure Developer】示例: 在中国区调用MSGraph SDK通过User principal name获取到User信息,如Object ID
|
20天前
|
开发工具 iOS开发 容器
【Azure Blob】关闭Blob 匿名访问,iOS Objective-C SDK连接Storage Account报错
【Azure Blob】关闭Blob 匿名访问,iOS Objective-C SDK连接Storage Account报错
|
Java 设计模式
java设计模式--原型设计模式 Prototype
所谓的原型即给我们一个对象 我们就可以无限复制出这个对象的副本  ,而不是引用这个对象   。  复制出来的副本 是一个个独立的对象 , 绝不是 原来对象的引用 。 这就要求设计到 java中的对象克隆技术  ,克隆的对象所在的类要实现Cloneable接口  以及覆盖 Object类的  clone()方法  。
684 0
|
11天前
|
监控 Java 调度
【Java学习】多线程&JUC万字超详解
本文详细介绍了多线程的概念和三种实现方式,还有一些常见的成员方法,CPU的调动方式,多线程的生命周期,还有线程安全问题,锁和死锁的概念,以及等待唤醒机制,阻塞队列,多线程的六种状态,线程池等
73 6
【Java学习】多线程&JUC万字超详解
|
4天前
|
Java 调度 开发者
Java并发编程:深入理解线程池
在Java的世界中,线程池是提升应用性能、实现高效并发处理的关键工具。本文将深入浅出地介绍线程池的核心概念、工作原理以及如何在实际应用中有效利用线程池来优化资源管理和任务调度。通过本文的学习,读者能够掌握线程池的基本使用技巧,并理解其背后的设计哲学。
|
4天前
|
缓存 监控 Java
Java中的并发编程:理解并应用线程池
在Java的并发编程中,线程池是提高应用程序性能的关键工具。本文将深入探讨如何有效利用线程池来管理资源、提升效率和简化代码结构。我们将从基础概念出发,逐步介绍线程池的配置、使用场景以及最佳实践,帮助开发者更好地掌握并发编程的核心技巧。