繁体   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