簡體   English   中英

如何使用 java 代碼將文件作為 blob 從 Internet 上傳到 Azure 存儲?

[英]How to upload a file from internet to azure storage as a blob using java code?

我想將文件直接從互聯網上傳到“mycontainer”中的 Azure blob 存儲,我不想先在本地上傳下載文件。 我想用java代碼來做這個,誰能幫我提供示例代碼。

根據我的理解,我認為您想直接將文件從互聯網 url 上傳到 Azure Blob 存儲。 您可以使用方法CloudBlob.startCopy(URI source)來實現您的需求。

這是我的示例代碼。

String connectionString = String.format("DefaultEndpointsProtocol=http;AccountName=%s;AccountKey=%s", ACCOUNT_NAME, ACCOUNT_KEY);
CloudStorageAccount account = CloudStorageAccount.parse(connectionString);
CloudBlobClient client = account.createCloudBlobClient();
CloudBlobContainer container = client.getContainerReference("mycontainer");
CloudBlockBlob blob = container.getBlockBlobReference("bing.txt");

String uri = "http://www.bing.com";
blob.startCopy(new URI(uri));

希望能幫助到你。

您必須在您的項目中添加此 Maven 依賴項。

 <dependency>
 <groupId>com.azure</groupId>
 <artifactId>azure-storage-blob</artifactId>
 <version>12.0.0</version>
 </dependency>

並添加以下導入。

import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
import com.azure.storage.blob.specialized.BlockBlobClient;

您可以使用以下代碼將新文件上傳到容器。

BlobClient blobClient = null;

try {
  String mConnectionstring = "DefaultEndpointsProtocol=https;AccountName=
         mystorageaccount;AccountKey
         =6xjXi/dA==;EndpointSuffix=core.windows.net";

// Create a BlobServiceClient object which will be used to create a container
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(mConnectionstring)
.buildClient();

// Create a unique name for the container
String containerName = "anycontainername";

// Create the container and return
// a container client object
BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerName);

// Get a reference to a blob
blobClient = containerClient.getBlobClient(file.getOriginalFilename());

// Note: We are creating BlockBlob instance.
BlockBlobClient blockBlobClient = blobClient.getBlockBlobClient();

blockBlobClient.upload(file.getInputStream(), file.getSize());

有關更多信息,您可以閱讀這篇關於使用 Java 的 Azure blob 存儲的文章。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM