Search code examples
javascripthtmlazureazure-blob-storageazure-storage

Is there a way to list Azure Blob container contents on HTML dropdown bar to be selected?


My API uses a HTML front-end for consumers to download files from my Azure Storage account. The issue is that consumers need to type in the exact name of the file to download what they want. I want to present the contents of the container through a dropdown bar, with each file being a selectable option. I'm new to Azure's services, so I was wondering if this was possible.

I've tried using the URI https://account-name.blob.core.windows.net/container-name?sas-token&restype=container&comp=list and parsing the file names from the XML, but I've been receiving errors. I also tried to use BlobServiceClient, however it hasn't been working in the script section of my HTML page.

Edit-

Error Message: XMLHttpRequest at 'https://account-name.blob.core.windows.net/container-name?sas-token&restype=container&comp=list' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Code:

    function listFiles () {
    var url = 'https://account-name.blob.core.windows.net/container-name?sas-token&restype=container&comp=list'
    var req = new XMLHttpRequest();
    req.open('GET', url, false);
    req.send(null);
    var xml = request.responseXML;
    var users = xml.getElementsByTagName("Blobs"); }

Solution

  • XMLHttpRequest at 'https://account-name.blob.core.windows.net/container-name?sas-token&restype=container&comp=list' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    I agree with Gaurav Mantri, Make sure you enable CORS to your Azure blob storage.

    By default, CORS is not enabled for Azure Blob Storage, which restricts cross-origin requests from being made.

    You can follow this MS Document to understand CORS policy.

    To enable CORS in Azure blob storage:

    Portal -> Your storage account -> Under setting(Resource sharing CORS) -> blobs service.

    Allowed origins = *
    Allowed methods = GET, HEAD, MERGE, DELETE, POST, PUT, OPTIONS, PATCH (For your environments it is better to add only the required methods)
    Allowed headers= *
    Exposed headers= *
    Max age = 86400
    

    After adding you can save the CORS policy.

    enter image description here

    Once your Cors policy is set, you can try with the same code to get the contents of the container.