Thursday, June 21, 2007

ASP "Save As" Dialog

Have you ever wanted to give a visitor to your web site an easy way to download a file without having to do a right click/save as? Or a way to bypass the way IE and other browsers autoload content into the browser when it recognizes the file type?

Here's a script to launch the "Save As" dialog box (teste din IE and FF). I created a file named 'save.asp'; all you do is feed it the name of the file you want to save.
qFile = ""
qFile = Request.Querystring("file")

Response.ContentType = "application/x-unknown" ' arbitrary
fn = qFile
FPath = "c:\Place\To\Save\The\File\" & fn
Response.AddHeader "Content-Disposition","attachment; filename=" & fn

Set adoStream = CreateObject("ADODB.Stream")
adoStream.Type = 1
Response.BinaryWrite adoStream.Read()
Set adoStream = Nothing

Simply pass in the name of the file you want the user to download as a querystring variable.

I'm calling it with a button instead of a link:
<input type="submit" value="Save it" onClick="window.location.href='save.asp?file=FileName'">
If you wanted to use a link, all you'd do is: <a href="save.asp?file=FileName">Save it</a>

It doesn't spawn a new browser window. It simply brings up the Save As dialog.

I've got it in action on my AddCaption site to allow visitors to easily save the image after they've added their text to it.


Srini said...

Is this code work fine in IIS 7.5. when the file size is greater than 2kb

Anonymous said...

Great article. How do I view and save a PDF file from ASP. The files are saved using a userID, so I need to get a pdf file associated with each user. Please help with some code.

Anonymous said...

this is not a save as function its just uploading a file to a location on local server; its missleading