0

I'm downloading a pdf file from Azure blob storage and specify the local file name and extension.

It downloads fine to the downloads directory but with the name Microsoft.WidowsAzure.Storage.Blob file name and no extension.

I want to specify the file name not the directory which is fine.

    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();
Mohamad Mousheimish
  • 1,641
  • 3
  • 16
  • 48
John
  • 45
  • 6

1 Answers1

0

The default .ToString() method for any class, unless overridden by that class, will print the fully qualified class name (as is happening in your case). Instead you need to use the blob's .Name property to get the key. Once you have the key, you can strip it down to just the filename part:

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

For safety (in terms of bad characters in the filename) you might want to consider using filename*= as described in RFC6266 with appropriate encoding:

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

See this question for more on that.

Community
  • 1
  • 1
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86