asp.net ashx handler prompting download instead of displaying file

I implemented a generic handler in my application which works great for images, but when I manually type the handler URL in the browser with the image’s querystring it prompts download instead of displaying. Here is my code:

public void ProcessRequest(HttpContext context)
        {
            if (this.FileName != null)
            {
                string path = Path.Combine(ConfigurationManager.UploadsDirectory, this.FileName);

                if (File.Exists(path) == true)
                {
                    FileStream file = new FileStream(path, FileMode.Open);
                    byte[] buffer = new byte[(int)file.Length];
                    file.Read(buffer, 0, (int)file.Length);
                    file.Close();
                    context.Response.ContentType = "application/octet-stream";
                    context.Response.AddHeader("content-disposition", "attachment; filename="" + this.FileName + """);
                    context.Response.BinaryWrite(buffer);
                    context.Response.End();
                }
            }
        }

I am using the octet-stream because I’m dealing with more than just images and I don’t always know the content type of the file. Thanks in advance!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The only way is to specify correct ContentType so the browser know what to do with receiving file, depending on installed plugins (for example, view pdf files in browser frame) and system assosiations (for example, offer to open document in MS Office instead of simple download)

You can try to specify Content Type depending on file extension, i.e.:

if(Path.GetExtension(path) == ".jpg")
   context.Response.ContentType = "image/jpeg";
else
   context.Response.ContentType = "application/octet-stream";

Method 2

If you store the ContentType as part of the files metadata, when you pull it back down your could use it.

theFile = GetFile(id)
context.Response.ContentType = theFile.Type;

Method 3

The content-disposition header is the one that causes your browser to show the download dialog. Remove that line and it will show in the browser.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x