Change the filename shown in IE for a dynamic content
Today I encountered this issue in one of the projects. Simply put, we have an ASPX page like www.venkatarangan.com/file/getit.aspx?id=4040 that is going to read a file say “Office2003.DOC” from filesystem and stream it. The actual file will depend on the ID that is passed. It will come from a folder that is not accessible through IIS or will come from a SQL Server BLOB column. In either case an user will see in IE’s dialog box the filename to be get it.aspx?id=4040 and not as “Office2003.DOC”.
We can modify the mimetype of the output of an ASPX page to say image/jpeg or anything by using the Response.ContentType property. It will be easy if we can specify the filename as well, but no property exists to do this in Response object. One way to solve it will be to create a virtual URL like /4040/office2003.doc. This URL doesn’t exist, it will be mapped to be handled by a HTTPModule and the HTTPModule does the streaming by parsing the URL and getting the ID number. Since in this case the filepath from IE’s perspective is Office2003.doc, IE will no problem in identifying the mimetype and launching MS Word with the file loaded.
HTTPModule seemed to be a round-about solution. That’s when my good friend Deepak Gulati of Microsoft came to rescue with this ASP code snippet (Thanks Deepak, I know I can count on you for these quick solutions. If you get a chance visit his photo blog)
<% 'If correct mime type is known use that Response.ContentType = "application/x-unknown" 'Arbitrary
fn = "blog.doc" 'Actual FileName FPath = "c:\temp\" & fn Response.AddHeader "Content-Disposition","attachment; filename=" & fn
Set adoStream = CreateObject("ADODB.Stream") adoStream.Open() adoStream.Type = 1 adoStream.LoadFromFile(FPath) Response.BinaryWrite adoStream.Read() adoStream.Close Set adoStream = Nothing Response.End %>
The above solution works by adding a “Content-Disposition” header as specified in RFC2183. This RFC seems to provide couple of useful customization possibilities, check it out. The code also shows a simple way to read a file and stream it using ASP/ADO.
1) How To Raise a “File Download” Dialog Box for a Known MIME Type – Microsoft Support KB
2) Explanation of Content-Disposition – MSDN Reference
While I was searching this, I came across this support article that uses a single API call to “URLDownloadToFile” for downloading and saving a file. The code works in VB6.0 thru’ .NET.