Rexam
Rexam

Reputation: 913

How to upload an image to Azure Blob Storage with v10 SDK?

I'm trying to upload an image on the Blob Storage of Microsoft Azure using SDK V10 in Angular.

The following is the code I currently use to connect to the Storage and list all the containers names:

// connect to the Blob Service
const pipeline = StorageURL.newPipeline(new AnonymousCredential(), {
    retryOptions: { maxTries: 4 },
    telemetry: { value: "HighLevelSample V1.0.0" }
});

const serviceURL = new ServiceURL(
    `${this.blobUri}/${environment.azureContainers.sasToken}`,
    pipeline
);

// List containers
let marker;
do {
    const listContainersResponse: Models.ServiceListContainersSegmentResponse = await serviceURL.listContainersSegment(
      Aborter.none,
      marker
    );

    marker = listContainersResponse.nextMarker;
      for (const container of listContainersResponse.containerItems) {
        console.log(`Container: ${container.name}`);
      }
} while (marker);

Now I would like to upload a file (specifically, a image) in one of the listed containers (doesn't matter which one for the purpose of this question), but from what I have read in the documentation, a filepath is required, but I don't have it. What I have instead is an object of type "File" in JS and, as far as I know, getting a filepath from the browser cannot be done due to security reasons!

Do you have any idea of how to achieve this? How can I upload an image to the Blob Storage in Angular?

Upvotes: 2

Views: 912

Answers (1)

Gaurav Mantri
Gaurav Mantri

Reputation: 136146

The example you referred to is for Node JS which has access to the file system. For uploading a file in the browser, you will need to make use of uploadBrowserDataToBlockBlob method.

From this samples link

  // Parallel uploading a browser File/Blob/ArrayBuffer in browsers with uploadBrowserDataToBlockBlob

  const browserFile = document.getElementById("fileinput").files[0];
  await uploadBrowserDataToBlockBlob(Aborter.none, browserFile, blockBlobURL, {
    blockSize: 4 * 1024 * 1024, // 4MB block size
    parallelism: 20, // 20 concurrency
    progress: ev => console.log(ev)
  });

Upvotes: 2

Related Questions