【问题标题】:How to Download a PDF file from Azure in ASP.NET MVC via Save Dialog如何在 ASP.NET MVC 中通过保存对话框从 Azure 下载 PDF 文件
【发布时间】:2015-10-02 08:35:25
【问题描述】:

我有一个存储在 Azure 存储上的文件,我需要从 ASP.NET MVC 控制器下载该文件。下面的代码实际上运行良好。

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

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

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

但在 Azure 中这不起作用。

【问题讨论】:

    标签: c# asp.net asp.net-mvc azure azure-storage


    【解决方案1】:

    假设当您说 Azure Storage 时您的意思是 Azure Blob Storage,还有其他两种方法无需将文件从存储实际下载到您的 Web 服务器,它们都涉及在您的 blob 上设置 Content-Disposition 属性。

    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();
      
    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.
      

    【讨论】:

      【解决方案2】:

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

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

      这个特殊的overload 接受一个字节数组、一个内容类型和一个目标文件名。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多