简体   繁体   中英

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

I want to upload file directly from internet to Azure blob storage in "mycontainer", I dont want to download file first in local the upload. I want to do this using java code, can anyone please help me with sample code.

Based on my understanding, I think you want to directly upload a file from internet url to Azure Blob Storage. You can use the method CloudBlob.startCopy(URI source) to implement your needs.

Here is my sample code.

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));

Hope it helps.

You have to add this maven dependency in your project.

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

And add the following imports.

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;

You can use the below code to upload a new file to the container.

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());

For more information you can read this article on Azure blob Storage using Java .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM