C# 如何通过保存对话框从ASP.NET MVC中的Azure下载PDF文件
我有一个存储在Azure存储上的文件,需要从ASP.NET MVC控制器下载。下面的代码实际上运行良好C# 如何通过保存对话框从ASP.NET MVC中的Azure下载PDF文件,c#,asp.net,asp.net-mvc,azure,azure-storage,C#,Asp.net,Asp.net Mvc,Azure,Azure Storage,我有一个存储在Azure存储上的文件,需要从ASP.NET MVC控制器下载。下面的代码实际上运行良好 string fullPath = ConfigurationManager.AppSettings["pdfStorage"].ToString() + fileName ; Response.Redirect(fullPath); 但是,PDF将在同一页面中打开。我希望通过“保存”对话框下载文件,以便用户保持在同一页面上。在搬到Azure之前,我可以写 return File(full
string fullPath = ConfigurationManager.AppSettings["pdfStorage"].ToString() + fileName ;
Response.Redirect(fullPath);
但是,PDF将在同一页面中打开。我希望通过“保存”对话框下载文件,以便用户保持在同一页面上。在搬到Azure之前,我可以写
return File(fullPath, "application/pdf", file);
但是Azure不起作用。您可以下载该文件,然后推送到web浏览器,以便用户能够保存
var fileContent = new System.Net.WebClient().DownloadData(fullPath); //byte[]
return File(fileContent, "application/pdf", "my_file.pdf");
这一特定操作需要一个字节数组、一个内容类型和一个目标文件名。假设您的意思是
Azure Blob Storage
,当您说Azure Storage
时,还有两种方法没有实际将文件从存储下载到web服务器,这两种方法都涉及在Blob上设置属性
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();
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.