user3006967
user3006967

Reputation: 3545

How to Download Azure blob file into download folder, not in browser

I want to put a button in page, and when user click the button, I want to download azure blob into download folder.

  1. I generate the blob link url:

    var downloadLink = blobService.getUrl('mycontainer', 'myblob', 'SAS_TOKEN');

  2. Once I get this url, I use this solution to download:

    var link = document.createElement("a");
    link.download = name;
    link.href = url;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    

I used the same in S3, the file can be downloaded in the same browser and into download folder, but for Azure, when I use this solution, it just open a new tab and display the contents in the browser.

Can anyone help to see why this? How to download the file instead of displaying the content in browser?

The url generated is:

https://myBucket.blob.core.windows.net/mycontainer/1000/rawEvents.json?se=2022-04-20T23%3A59%3A59Z&sp=rwdlacup&sv=2018-03-28&ss=b&srt=sco&sig=EzsjwqKfYmwwUo2n1ySkCBAsTfW35ic8M8F6tfuXEPo%3D

If if click this url, it can read contents as well.

Upvotes: 0

Views: 2603

Answers (1)

Alex
Alex

Reputation: 18526

You need to make sure that the Content-Type and Content-Disposition headers have values which trigger your browser to download the files. Especially Content-Disposition is important.

Content-Type: application/octet-stream
Content-Disposition: attachment

You can either set the content disposition on the blob itself

        var blob = container.GetBlobReference(userFileName);
        blob.Properties.ContentDisposition = "attachment";
        blob.SetProperties();

or add it to your SAS token (see also corresponding blog post).

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("videos");
        string userFileName = service.FirstName + service.LastName + "Video.mp4";
        CloudBlockBlob blob = container.GetBlockBlobReference(userFileName);
        SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
        {
            Permissions = SharedAccessBlobPermissions.Read,
            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1)
        };
        SharedAccessBlobHeaders blobHeaders = new SharedAccessBlobHeaders()
        {
            ContentDisposition = "attachment; filename=" + userFileName
        };
        string sasToken = blob.GetSharedAccessSignature(policy, blobHeaders);
        var sasUrl = blob.Uri.AbsoluteUri + sasToken;//This is the URL you will use. It will force the user to download the video.

Upvotes: 2

Related Questions