Friday, April 06, 2007
Serving files from server
A Common Question I often receive questions about file serving from both my colleagues and users of different discussion groups. There are two ways a file can be served from server to client. One way is to automatically offer the user to open or save a file and another way is to force web browser to open the file. Implementation is quite simple and to be able to implement one of the options developer should be familiar with RFC 1806 which defines “Content-Disposition” header.
Solution The first thing that should be done is getting the content of the file. Another thing that should be known is the file type and its MIME type. When file is read into a byte array buffer, serving of file can start.
The key is in setting the right value of “Content-Disposition” header. The header can receive two values: “inline” and “attachment”. If one wants to open a file directly in browser then “inline” should be used. The “inline” value will tell browser to open the content directly in browser’s window and defined content type will tell the browser how to open the file. If one wants to offer an “Open / Save” dialog so that user can choose the action then “attachment” value should be used.
Examples Next example shows how PDF file can be read and served to browser so that browser automatically opens it in its window; example is written in C#:
FileStream fs = File.OpenRead("filename.pdf");
Response.AppendHeader("Content-disposition", "inline; filename=" + "filename.pdf"); Response.AppendHeader("Pragma", "no-cache"); Response.AppendHeader("Expires", "Mon, 1 Jan 2000 05:00:00 GMT"); Response.AppendHeader("Last-Modified", DateTime.Now.ToString() + "GMT"); Response.Expires = -1; Response.ContentType = "application/pdf"; Response.BinaryWrite(GetWholeFileContent(fs, (int)fs.Length)); Response.Flush();
In example above GetWholeFileContent is custom method that returns byte array from input stream.
If one would like to offer an “Open/Save” dialog instead of automatically opening the file then only change in example above would be change of “Content-Disposition” header from “inline” to “attachment”.
If different file type should be served and not the PDF file type then instead of “application/pdf” the right content type should be set. To find out which content type should be set visit http://www.iana.org/assignments/media-types/.
posted by Popovic Sasa
0 Comments:
+ Blog Home
|