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

代码,uploadWithResponse ,Java ,ChatGTP · 浏览次数 : 67

小编点评

**Java Storage SDK uploadWithResponse 示例代码** ```java import com.azure.storage.blob.BlobClient; import com.azure.storage.blob.BlobContainerClient; import com.azure.storage.blob.BlobServiceClient; import com.azure.storage.blob.BlobServiceClientBuilder; // 连接字符串 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); // 创建上传选项 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)); // 设置请求条件 BlobUploadOptions options = new BlobUploadOptions() .setInputStream(inputStream) .setLength((long) content.length()) .setHttpHeaders(new BlobHttpHeaders().setContentType("text/plain")) .setRequestConditions(new BlobRequestConditions().setIfNoneMatch("*\")); // 执行上传 Response<BlockBlobItem> rsp = blobClient.uploadWithResponse(options, null, null); // 检查状态码 if (rsp.getStatusCode() == 201) { // 上传成功 System.out.println("append content successful........"); } else { // 上传失败 System.out.println("upload failed with status code " + rsp.getStatusCode()); } ``` **注意:** * 代码中的 `connectionString`、`containerName` 和 `fileName` 要根据您的实际配置进行修改。 * 代码中的 `content` 应该包含要上传的字符串内容。 * 此代码仅用于上传文件,如果您需要上传其他类型的对象,请使用相应的类和方法。

正文

问题描述

查看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

 

 

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

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

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

【Azure 存储服务】Azure Blob Storage SDK 升级失败,遇见 Unsatisfied Dependency Exception 和 Unexpected Length Exception

问题描述 在升级Java Azure Blob Storage SDK的过程中,先后遇见了 UnsatisfiedDependencyException 和 UnexpectedLengthException. 错误一:Org.springframework.beans.factory Unsati

【Azure 存储服务】存储在Azure Storage Table中的数据,如何按照条件进行删除呢?

问题描述 如何按条件删除 Storage Table 中的数据,如果Table中有大量的条记录需要删除,Java代码如何按条件删除 Table中的数据(Entity)? (通过Azure Storage Explorer工具是可以删除,但是由于数据量太大,人工操作耗时太久,所以需要使用Java代码完

【Azure 存储服务】多设备并发往 Azure Storage Blob 的 Container 存数据是否可以

问题描述 多设备并发往 Azure Storage Blob 的 Container 存数据是否可以? 问题解答 可以! Azure Storage 是支持的并发存储数据的,Blob 可以使用乐观并发或悲观并发模型的,具体实现可以参考文档:https://docs.microsoft.com/zh-

【Azure 存储服务】Azure Data Lake Storage (ADLS) Gen2 GRS Failover是否支持自动切换或者手动切换到灾备的终结点呢?

问题描述 在Azure的存储服务中,介绍灾备恢复和Storage Account故障转移的文档中,有一句话“Account failover is not supported for storage accounts with a hierarchical namespace enabled.” 而

【Azure 存储服务】如何查看Storage Account的删除记录,有没有接口可以下载近1天删除的Blob文件信息呢?

问题描述 如何查看Storage Account的删除记录,有没有接口可以下载近1天删除的Blob文件信息呢?因为有时候出现误操作删除了某些Blob文件,想通过查看删除日志来定位被删除的文件信息。 问题解答 如果没有启用Storage Account的软删除功能,则没有办法直接查看近期有删除的Blo

【Azure 存储服务】MP4视频放在Azure的Blob里面,用生成URL在浏览器中打开之后,视频可以正常播放却无法拖拽视频的进度

问题描述 把MP4视频放在Azure的Blob里面,用生成URL在浏览器中打开之后,视频可以正常播放却无法拖拽视频的进度,这是什么情况呢? 问题解答 因为MP4上传到Azure Blob后,根据公开的权限,可以直接通过Storage Blob URL +/ Blob Container + / Bl

【Azure 存储服务】Azure Storage Account Queue中因数据格式无法处理而在一个小时内不在可见的问题

问题描述 在从Storage Account 队列中获取数据(Queue),在门户中,明显看见有数据,但是通过消费端代码去获取的时候,就是无法获取到有效数据的情况。获取消息的代码如下: 问题解答 经过对 receiveMessages 方法定义的查询,第二个参数,第三个参数的两个时间表示的意思为 消

【Azure 存储服务】.NET7.0 示例代码之上传大文件到Azure Storage Blob (一)

问题描述 在使用Azure的存储服务时候,如果上传的文件大于了100MB, 1GB的情况下,如何上传呢? 问题解答 使用Azure存储服务时,如果要上传文件到Azure Blob,有很多种工具可以实现。如:Azure 门户, Azure Storage Explorer, 命令行工具 az copy

【Azure 存储服务】.NET7.0 示例代码之上传大文件到Azure Storage Blob (二)

问题描述 在上一篇博文(【Azure 存储服务】.NET7.0 示例代码之上传大文件到Azure Storage Blob (一):https://www.cnblogs.com/lulight/p/17061631.html)中,介绍了第一种分片的方式上传文件。 本文章接着介绍第二种方式,使用 M