【问题标题】:Azure blob DownloadToStream specify local file nameAzure blob DownloadToStream 指定本地文件名
【发布时间】:2019-08-29 07:40:00
【问题描述】:

我正在从 Azure Blob 存储下载一个 pdf 文件并指定本地文件名和扩展名。

它可以很好地下载到下载目录,但名称为Microsoft.WidowsAzure.Storage.Blob 文件名且没有扩展名。

我想指定文件名而不是目录。

    MemoryStream memStream = new MemoryStream();
    blockBlob.DownloadToStream(memStream);
    HttpContext.Current.Response.ContentType = blockBlob.Properties.ContentType.ToString();
    // Response.AddHeader("Content-Disposition", "Attachment; filename=" + blobName.ToString());    
    HttpContext.Current.Response.AddHeader("Content-Disposition", "Attachment; filename=" + blockBlob.ToString());
    HttpContext.Current.Response.AddHeader("Content-Length", blockBlob.Properties.Length.ToString());
    HttpContext.Current.Response.BinaryWrite(memStream.ToArray());
    HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.Close();

【问题讨论】:

    标签: c# pdf blob azure-storage


    【解决方案1】:

    任何类的默认 .ToString() 方法,除非被该类覆盖,否则将打印完全限定的类名(就像您的情况一样)。相反,您需要使用 blob 的 .Name 属性来获取密钥。获得密钥后,您可以将其剥离为文件名部分:

    string fileName = Path.GetFileName(blob.Name);
    HttpContext.Current.Response.AddHeader("Content-Disposition", "Attachment; filename=" + fileName);
    

    为了安全(就文件名中的错误字符而言),您可能需要考虑使用 filename*=,如 RFC6266 中所述,采用适当的编码:

    string encodedFileName = Server.UrlEncode(Path.GetFileName(blob.Name), Encoding.UTF8);
    HttpContext.Current.Response.AddHeader("Content-Disposition", "Attachment; filename*=UTF-8''" + fileName);
    

    See this question 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2014-08-10
      • 1970-01-01
      • 2018-03-10
      • 2018-02-23
      • 2014-09-19
      • 2012-04-15
      • 1970-01-01
      • 2016-12-25
      • 2019-04-03
      相关资源
      最近更新 更多