問(wèn)題描述
查看Java Storage SDK,想找一個(gè) uploadWithResponse 的示例代碼踢京,但是通過(guò)全網(wǎng)搜索翔试,結(jié)果沒(méi)有任何有幫助的代碼爆土。使用最近ChatGPT來(lái)尋求答案鹉究,得到非常有格式的內(nèi)容:
| 問(wèn):java azure storage account to use uploadWithResponse |
答:To use the uploadWithResponse
method with the Azure Blob Storage client library for Java, follow these steps:
- 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>
- 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;
- Create a
BlobServiceClient
instance using your storage account connection string:
String connectionString = "your_connection_string";
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectionString).buildClient();
- 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);
- 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.
繼續(xù)追問(wèn):BlobParallelUploadOptions with string content
答:(前面4步的答案一樣宇立,第五步的內(nèi)容為)
- Convert the string content to an
InputStream
and set upBlobParallelUploadOptions
:
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
*在繼續(xù)問(wèn):如何使用 “To avoid overwriting, pass "" to setIfNoneMatch(String ifNoneMatch). how to use the setifnonematch” **
| 答:(前面4步的答案一樣,第五步的內(nèi)容為)
- Set up
BlobUploadOptions
withsetIfNoneMatch
:
BlobUploadOptions options = new BlobUploadOptions()
.setInputStream(inputStream)
.setLength((long) content.length())
.setHttpHeaders(new BlobHttpHeaders().setContentType("text/plain"))
.setRequestConditions(new BlobRequestConditions().setIfNoneMatch("*"));
- Upload the string content using the
uploadWithResponse
method withBlobUploadOptions
:
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.
問(wèn)題解答
根據(jù)ChatGPT提供的三部分信息自赔,通過(guò)人力拼接和測(cè)試妈嘹。得到了成功執(zhí)行的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);
//準(zhǔn)備content并且初始化blob parallel upload options對(duì)象
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........");
}
說(shuō)明:
1) content 中為需要寫(xiě)入Blob的內(nèi)容
2) 把string轉(zhuǎn)換為以UTF_8編碼的input stream
3) 根據(jù) input stream來(lái)初始化 blob paralle upload options對(duì)象
4) 設(shè)置 Request Conditions,當(dāng)不需要重寫(xiě)的時(shí)候匿级,可以使用 setIfNoneMatch("*")蟋滴。如果操作的文件存在染厅,則會(huì)出現(xiàn) Status code 409, BlobAlreadyExistss 提示痘绎。
5) 調(diào)用upload with response方法,獲取返回值肖粮,如果 返回值得status code為 201孤页,表示Storage Account接受了這次 blob 內(nèi)容的改動(dòng)。
運(yùn)行效果展示圖
參考資料
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 存儲(chǔ)客戶端庫(kù) : 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
當(dāng)在復(fù)雜的環(huán)境中面臨問(wèn)題涩馆,格物之道需:濁而靜之徐清行施,安以動(dòng)之徐生允坚。 云中,恰是如此!