I have a file stored on Azure storage that I need to download from ASP.NET MVC controller. The code below actually works fine.
string fullPath = ConfigurationManager.AppSettings["pdfStorage"].ToString() + fileName ;
Response.Redirect(fullPath);
However, the PDF opens in the same page. I want the file to be downloaded via a Save dialog box, so the user stays on the same page. Before moving to Azure, I could write
return File(fullPath, "application/pdf", file);
But with Azure that doesn't work.
Assuming you mean Azure Blob Storage
when you say Azure Storage
, there are two other ways without actually downloading the file from storage to your web server and both of them involve setting Content-Disposition
property on your blob.
If you want the file to always download when accessed via a URL, you can set blob's content-disposition property.
var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
var blobClient = account.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("container-name");
var blob = container.GetBlockBlobReference("somefile.pdf");
blob.FetchAttributes();
blob.Properties.ContentDisposition = "attachment; filename=\"somefile.pdf\"";
blob.SetProperties();
However if you want the file to be downloaded sometimes and displayed in the browser other times, you can create a shared access signature and override the content-disposition property in the SAS and use that SAS URL for downloading.
var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
var blobClient = account.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("container-name");
var blob = container.GetBlockBlobReference("somefile.pdf");
var sasToken = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
{
Permissions = SharedAccessBlobPermissions.Read,
SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(15),
}, new SharedAccessBlobHeaders()
{
ContentDisposition = "attachment; filename=\"somefile.pdf\"",
});
var downloadUrl = string.Format("{0}{1}", blob.Uri.AbsoluteUri, sasToken);//This URL will always do force download.
You could download the file and then push to the web browser so the user will be able to save.
var fileContent = new System.Net.WebClient().DownloadData(fullPath); //byte[]
return File(fileContent, "application/pdf", "my_file.pdf");
This particular overload takes a byte array, a content type and a destination file name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With