Reputation: 3545
I want to put a button in page, and when user click the button, I want to download azure blob into download folder.
I generate the blob link url:
var downloadLink = blobService.getUrl('mycontainer', 'myblob', 'SAS_TOKEN');
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:
If if click this url, it can read contents as well.
Upvotes: 0
Views: 2603
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