如何通过"保存对话框"从ASP.NET MVC中的Azure下载PDF文件

Har*_*hah 6 c# asp.net asp.net-mvc azure azure-storage

我有一个存储在Azure存储上的文件,我需要从ASP.NET MVC控制器下载.下面的代码实际上工作正常.

string fullPath =  ConfigurationManager.AppSettings["pdfStorage"].ToString() + fileName ;
Response.Redirect(fullPath);
Run Code Online (Sandbox Code Playgroud)

但是,PDF将在同一页面中打开.我希望通过"保存"对话框下载文件,以便用户保持在同一页面上.在转移到Azure之前,我可以写

return File(fullPath, "application/pdf", file);
Run Code Online (Sandbox Code Playgroud)

但是Azure无法正常工作.

Gau*_*tri 5

假设你的意思是,Azure Blob Storage当你说时Azure Storage,还有另外两种方法没有实际将文件从存储器下载到你的web服务器,它们都涉及Content-Disposition在你的blob上设置属性.

  1. 如果您希望在通过URL访问时始终下载文件,则可以设置blob的content-disposition属性.

    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();
    
    Run Code Online (Sandbox Code Playgroud)
  2. 但是,如果您希望有时下载文件并在浏览器中显示其他时间,则可以创建共享访问签名并覆盖SAS中的content-disposition属性并使用该SAS URL进行下载.

        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.
    
    Run Code Online (Sandbox Code Playgroud)


sca*_*tag 1

您可以下载该文件,然后推送到网络浏览器,以便用户能够保存。

var fileContent = new System.Net.WebClient().DownloadData(fullPath); //byte[]

return File(fileContent, "application/pdf", "my_file.pdf");
Run Code Online (Sandbox Code Playgroud)

此特定重载采用字节数组、内容类型和目标文件名。