Displaying a file on the browser

  • Thread starter Thread starter AAaron123
  • Start date Start date
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";

}

}
 
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)
 
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
 
Back
Top