How to upload a PDF file from Azure to ASP.NET MVC using the Save dialog box

I have a file stored in Azure storage that I need to download from an ASP.NET MVC controller. The code below really works fine.

string fullPath = ConfigurationManager.AppSettings["pdfStorage"].ToString() + fileName ; Response.Redirect(fullPath); 

However, the PDF opens on the same page. I want the file to be downloaded through the Save dialog, so the user stays on one page. Before moving on to Azure, I could write

 return File(fullPath, "application/pdf", file); 

But this does not work with Azure.

+6
source share
2 answers

You can upload the file and then click on the web browser so that the user can save.

 var fileContent = new System.Net.WebClient().DownloadData(fullPath); //byte[] return File(fileContent, "application/pdf", "my_file.pdf"); 

This particular overload accepts a byte array, content type, and destination file name.

+1
source

Assuming you mean Azure Blob Storage when you say Azure Storage , there are two other ways without actually uploading the file from the vault to your web server, and both of these include setting the Content-Disposition on your blob.

  • If you want the file to always be loaded when accessed via the URL, you can set the property-scope of the blob content.

     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 load and display sometimes in the browser at other times , you can create a shared signature and override the content-disposition property in SAS and use the URL to download SAS.

      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. 
+5
source

All Articles