Displaying a file on the browser

A

AAaron123

If I want to download and display a file on the browser I use the following
code.

Works OK but I wonder if there is a better way to check if the browser can
display a file.

And also, The error message get added to the anchor that is in the aspx file
and they are both displayed as desired, but the image displays without the
anchor showing so the user can not navigate off the page.



Thanks for any help on either question





private void ViewFile(FileInfo file)

{

Response.Clear();

Response.AppendHeader("Content-Disposition", "filename=" + file.Name);

String TypeOfContent = GetContentTypeFromFileExt(file.Extension);

Response.ContentType = TypeOfContent;

if (TypeOfContent.StartsWith("text/") | TypeOfContent.StartsWith("image/"))

{

//Only send if it can be displayed

Response.WriteFile(file.FullName);

}

else

{

Response.Clear();

Response.Write("Can display only text and image files");

}

}





private static string GetContentTypeFromFileExt(string fileExtension)

{

//Retrieve content-type from the system registry given a file extension

RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(fileExtension);

try

{

return regKey.GetValue("Content Type",
"application/octet-stream").ToString();

}

catch (Exception)

{

return "application/octet-stream";

}

}
 
B

bruce barker

if it an image then you need to render html that has an <img> tag, which
will make another request to get the actual image. use an url arg, or
diffenent page name for the actual image fetch.

-- bruce (sqlwork.com)
 
A

AAaron123

Is there anything wrong with the way the code below does it.
Seems simpler.

I'm just wondering if I can ask the browser if it supports a file type
instead of assuming that if TypeOfContent.StartsWith text or image it does.
I'm sure that is not general enough.

Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top