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

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

时间:2023-05-08 21:56:03浏览次数:63  
标签:Java string 示例 代码 storage content blob azure new

问题描述

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

 

 

标签:Java,string,示例,代码,storage,content,blob,azure,new
From: https://www.cnblogs.com/lulight/p/17383272.html

相关文章

  • Java数组
    Java数组Java中,数组是用来存储固定大小的同类型元素。声明数组变量声明语法:dataType[]arrayRefVar;//首选方法dataTypearrayRefVar[];//效果相同,但不是首选例:double[]myList;doublemyList[];创建数组语法:arrayRefVar=newdataType[arraySize];......
  • java基于ssm的求职招聘管理系统、校园求职招聘管理系统,附源码+数据库,适合毕业设计、课
    1、项目介绍​该求职招聘网站基于B/S架构,采用SSM框架,运用JSP网页开发技术,并结合MySQL数据库,为招聘者和求职者搭建了一个高效、便捷的网络招聘平台。系统总共有三个角色:求职者、招聘者、管理员​本系统分别为前台求职招聘和后台系统管理,功能如下:​1.前台求职招聘​前台首......
  • 20天学会 java
    环境搭建,基础知识,高级知识,项目20天学会java00.java介绍01.java环节搭建,IDEA,java语言02.java语法,运算符,随机数03.java分支,循环,控制关键字04.数组,set,collections,map,集合05.方法06.面试对象基础07.常用api08.综合项目实战09.IO10.多线程11.网络编程12.高级技术:单元......
  • Java保留有效小数与百分数
    Java保留有效小数与百分数1.有效小数/***保留有效小数*@paramtargetForm目标形式*@paramoriginNum初始数字*@return有效小数*/publicStringgetSignificantDecimal(StringtargetForm,StringoriginNum)......
  • Java后端真实、靠谱、强大的面试题网站:面试梯
    ​ 本文分享一个给力的Java后端面试题网站:面试梯。网址:https://offer.skyofit.com这套题真实、高频、全面、有详细答案、保你稳过面试,让你成为offer收割机。题目包括:Java基础、多线程、JVM、数据库、Redis、Shiro、Spring、SpringBoot、MyBatis、MQ、ELK、分布式、SpringCloud......
  • 学习JavaScript数据结构与算法 第五章
    五,队列和双端队列我们已经学习了栈。队列和栈非常类似,但是使用了与后进先出不同的原则。双端队列是一种将栈的原则和队列的原则混合在一起的数据结构。5.1队列数据结构队列是遵循先进先出(FIFO,也称为先来先服务)原则的一组有序的项。队列在尾部添加新元素,并从顶部移除元素。最......
  • 谁想和我一起做低代码平台!一个可以提升技术,让简历装x的项目
    序言正如文章标题所述,最近一段时间低代码这个概念非常的火,但其实在不了解这个东西的时候觉得它真的很炫酷,从那时就萌生了做一个低代码平台的想法。但随着时间的变化,现在市面上低代码各个业务方向的平台都有了,可能已经错失了占领市场的先机,但我还是想要尝试一下,因为不仅仅是业务......
  • 第七次java
    1、 给定一个有9个整数(1,6,2,3,9,4,5,7,8)的数组,先排序,然后输出排序后的数组的值。2、packageyjwj;3、4、importjava.util.Arrays;5、6、publicclasstext1{7、8、 publicstaticvoidmain(String[]args){9、 //TODOAuto-generatedmethodstub10、inta[]={......
  • 环形队列的实现 [详解在代码中]
    1packageDataStructures.Queue.Array.Exerice;23/**4*@authorLoe.5*@projectDataStructures&Algorithms6*@date2023/5/87*@ClassInfo环形队列8*主要使用取模的特性来实现环形特征9*/10publicclassCirularQue......
  • 第六次java
    1.编写一个简单程序,要求数组长度为5,静态赋值10,20,30,40,50,在控制台输出该数组的值    2.packagefkx;3.4.publicclasstext1{5.6. publicstaticvoidmain(String[]args){7. //TODOAuto-generatedmethodstub8.inta[]={10,20,30,40,50};9.for(inti=0;i<a......