Search This Blog

Monday, May 31, 2010

How to display documents( *.txt, *.doc, *.pdf etc) and videos through ASP.NET

To display documents or videos through ASP.NET we need to first know the type of file to be displayed. In this method, ReturnExtension,  we will pass the extension of the file (eg, .html, .doc, .txt, .zip, .pdf, .mpeg etc) and will get the "content type" recognised by windows as string...

private string ReturnExtension(string fileExtension)
{
switch (fileExtension)
{
case ".htm":

case ".html":

case ".log":

      return "text/HTML";

case ".txt":

    return "text/plain";

case ".doc":

   return "application/ms-word";

case ".tiff":

case ".tif":

return "image/tiff";

case ".asf":
return "video/x-ms-asf";

case ".avi":
return "video/avi";

case ".zip":
return "application/zip";

case ".xls":
case ".csv":
return "application/vnd.ms-excel";

case ".gif":
return "image/gif";

case ".jpg":
case "jpeg":
return "image/jpeg";

case ".bmp":
return "image/bmp";

case ".wav":
return "audio/wav";

case ".mp3":
return "audio/mpeg3";

case ".mpg":
case "mpeg":
return "video/mpeg";

case ".rtf":
return "application/rtf";

case ".asp":
return "text/asp";

case ".pdf":
return "application/pdf";

case ".fdf":
return "application/vnd.fdf";

case ".ppt":
return "application/mspowerpoint";

case ".dwg":
return "image/vnd.dwg";

case ".msg":
return "application/msoutlook";

case ".xml":
case ".sdxl":
return "application/xml";

case ".xdp":
return "application/vnd.adobe.xdp+xml";

default:
return "application/octet-stream";

}
}
 
You can add your own extensions in this if you wish.
 
Now we have the filename and extension , so displaying it is easy task.
 
using System.IO;

public bool ShowFile(FileInfo file)
{

// Checking if file exists

if (file.Exists)
{

// Clear the content of the response
HttpContext.Current.Response.ClearContent();

// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);

// Add the file size into the response header
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());

// Set the ContentType
HttpContext.Current.Response.ContentType = ReturnExtension(file.Extension.ToLower());

// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
HttpContext.Current.Response.TransmitFile(file.FullName);

// End the response
HttpContext.Current.Response.End();
}

}
 
You can also display the file if it is saved in database in binary format. Just provide the correct extension (type of file) and instead of "TransmitFile" use "BinaryWrite" method and pass the byte array.
 
Cheers

No comments:

Post a Comment