Downloading Files - Forcing the File Download Dialog
page 1 of 1
Published: 03 Nov 2003
Abstract
Ever try to force the "Download File" dialog in a clients's browser window when you download files that may be supported with a MIME type? Here is an example that works with many versions of IE.
by Steve Sharrock
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 146128/ 1527

This example illustrates a simple technique to download files of any type from you web application to the client browser. In addition to setting the MIME types, the example shows how to force the Download File dialog that allows the user to either run or save the file, even if the file type would normally display in the browser's window.

On my personal site (http://www.sharkcode.com ), I allow the user to download my resume in various formats including Microsoft Word, HTML, Rich Text and Plain Text. I found that for most users (with IE) the correct application was automatically used to view the document from within their browser (such as Word types like .doc). In all cases, however, I wanted the file to be saved to the client's workstation, rather than simply being displayed by the browser. When I hosted my own site, I could do this by setting the HTTP Headers with "content-disposition" to force the Download File dialog. Now, using the .NET Response object, I can set these headers directly.

The basic ingredients of this example are quite simple and can be found in a Microsoft article at (http://support.microsoft.com/directory/article.asp?ID=KB;EN-US;q306654&lex).

The Microsoft article includes the following code snippet:

private void Page_Load(object sender, System.EventArgs e)
{
  //Set the appropriate ContentType.
  Response.ContentType = "Application/pdf";
  //Get the physical path to the file.
  string FilePath = MapPath("acrobat.pdf");
  //Write the file directly to the HTTP content output stream.
  Response.WriteFile(FilePath);
  Response.End();
}

I used this example to write a simple method that accepts a file name as input and a boolean that will force the File Download dialog which allows the client to either run, or save this file to their local workstation.

private void DownloadFile( string fname, bool forceDownload )
{
  string path = MapPath( fname );
  string name = Path.GetFileName( path );
  string ext = Path.GetExtension( path );
  string type = "";
  // set known types based on file extension  
  if ( ext != null )
  {
    switch( ext.ToLower() )
    {
    case ".htm":
    case ".html":
      type = "text/HTML";
      break;
  
    case ".txt":
      type = "text/plain";
      break;
     
    case ".doc":
    case ".rtf":
      type = "Application/msword";
      break;
    }
  }
  if ( forceDownload )
  {
    Response.AppendHeader( "content-disposition",
        "attachment; filename=" + name );
  }
  if ( type != "" )   
    Response.ContentType = type;
  Response.WriteFile( path );
  Response.End();    
}

The first few lines of code simply convert the file name argument into a physical path (on the server) and get the various component parts of the name. I only handle the file extension of known types that I'm currently using, but this could be extended to support additional MIME types (see the Microsoft article).

If the forceDownload boolean is true, I use the Response.AppendHeader method to add the "content-disposition" which forces the File Download (save) dialog.

I didn't find a lot of online help with the "content-disposition" header. In fact, it may even be on its way out in the future. But this currently works fine with IE 6 (and several prior version of IE upon which I've tested).

I recently found some posts on the ASPAlliance lists that also recommend setting Response.ContentType = "application/x-msdownload" to force the browser's download dialog. This should be especially useful when the type would otherwise be "application/octet-stream".

Visual Basic Example

Thanks to Mike Harber , I'm able to show the VB.NET version of the C# code example shown above. Thanks Mike.

Private Sub DownloadFile(ByVal fname As String, ByVal forceDownload As Boolean)
  Dim path As Path
  Dim fullpath = path.GetFullPath(fname)
  Dim name = path.GetFileName(fullpath)
  Dim ext = path.GetExtension(fullpath)
  Dim type As String = ""

  If Not IsDBNull(ext) Then
      ext = LCase(ext)
  End If

  Select Case ext
      Case ".htm", ".html"
          type = "text/HTML"
      Case ".txt"
          type = "text/plain"
      Case ".doc", ".rtf"
          type = "Application/msword"
      Case ".csv", ".xls"
          type = "Application/x-msexcel"
      Case Else
          type = "text/plain"
  End Select

  If (forceDownload) Then
      Response.AppendHeader("content-disposition", _
      "attachment; filename=" + name)
  End If
  If type <> "" Then
      Response.ContentType = type
  End If

  Response.WriteFile(fullpath)
  Response.End()

End Sub

Send your comments and let me know what you think of this article: steve@sharkcode.com

Steve Sharrock - www.SharkCode.com and www.AspAlliance.com/shark


Article Feedback

Title:  
Name:  
Url: ( Optional )
Comment:  
Please add 3 and 7 and type the answer here:

User Comments

Title: Good Help   
Name: Juan
Date: 5/5/2008 10:57:43 AM
Comment:
I have 1 question how one can know where the user click (on OPEN, SAVE or CANCEL) button of file download dialog box. How we handle the events for 'File Download' popup.

Waitting for Reply...

Juan
elavee@gmail.com
Title: Save Success   
Name: Elizanna
Date: 4/15/2008 8:23:08 AM
Comment:
As simple as. Worked successfully!
Thanks.
Title: Save Dialog box not working in IE6   
Name: Ganesan S
Date: 4/11/2008 1:51:20 AM
Comment:
Your code is working fine with IE7 and Mozilla, but it's not working in IE6. Please guide me.
Title: download mp3 song   
Name: pravin
Date: 4/1/2008 4:47:40 AM
Comment:
i want to design song download website in asp.net.
i store the path of the song in the database,when user select song ,the download window should open saying where to download on pc and then progress window




can anybody help me .........
Title: Down load   
Name: sunil
Date: 3/25/2008 7:24:23 AM
Comment:
i used the above source code for down load .pdf file.
but i got an error- "ex = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}"
what can i do for this problem
Title: About Open/Save   
Name: Hameed
Date: 3/18/2008 3:15:46 AM
Comment:
I cant able to open the file which has opened through open/save dialog box why? I want to know the reason

Regards
Hameed
Title: Extrodinory   
Name: Ravikumar
Date: 3/1/2008 6:21:58 AM
Comment:
thank you
your article was very usefull and i need to get the file path from the user by the filedialog
Title: Good Stuff   
Name: Balaji
Date: 2/25/2008 6:13:10 AM
Comment:
It is a very good article. It helped me a lot in crossing a hurdle, which i was facing in my project.
Title: Good Help   
Name: Rakesh Bhavsar
Date: 2/14/2008 4:18:38 AM
Comment:
Hi! guys
This is a very nice help for opening any type of file in browser or into the content type editor.
I have 1 question how one can know where the user click (on OPEN, SAVE or CANCEL) button of file download dialog box. How we handle the events for 'File Download' popup.

Waitting for Reply...
Rakesh
rakeshnb@mechsoftgroup.com
(INDIA)
Title: Downloading Time   
Name: Vignesh
Date: 2/11/2008 11:30:17 PM
Comment:
Hai, While downloading, if the time exceeds to download takes more than 10min, it should automatically stops downloading with error message. How to implement this.. Can any help???
Title: Problem with firefox   
Name: sudha
Date: 1/23/2008 3:17:28 AM
Comment:
Great article - very useful - but in Firefox, the save dialog opens, and it saves the file but without a file extension! It works great in IE. Any suggestions on how to fix this?
awaiting..
send ur reply @
rathi.sudha13@gmail.com
Title: Thanks   
Name: Chloe
Date: 12/13/2007 4:10:36 AM
Comment:
When I tried it with the VB.NET code I had a number of warnings etc.
Other than this it was very helpful.

Here is the code which did not create any warnings.

Private Sub DownloadFile(ByVal strPathFile As String, ByVal bForceDownload As Boolean)
Dim strPath, strFileName, strExt, strType As String

strPath = System.IO.Path.GetFullPath(strPathFile)
strFileName = System.IO.Path.GetFileName(strPath)
strExt = System.IO.Path.GetExtension(strPath)

If Not IsDBNull(strExt) Then strExt = LCase(strExt)

Select Case strExt
Case ".htm", ".html" : strType = "text/HTML"
Case ".txt" : strType = "text/plain"
Case ".doc", ".rtf" : strType = "Application/msword"
Case ".csv", ".xls" : strType = "Application/x-msexcel"
Case Else : strType = "text/plain"
End Select

If bForceDownload Then Response.AppendHeader("content-disposition", "attachment; filename=" + strFileName)
If strType <> "" Then Response.ContentType = strType

Response.WriteFile(strPath)
Response.End()

End Sub
Title: Working in Callback?   
Name: Suresh
Date: 12/11/2007 1:23:24 AM
Comment:
Hi,

Is it working in asyncronous postback?

Might be silly. But details would be great help!

Thanks,
Suresh.
Title: Download file on postback: Firefox problem   
Name: Andres
Date: 12/3/2007 7:24:06 AM
Comment:
Hi all,
I have a page (C# ASP.NET) with a link button which when clicked, executes a postback that downloads a file for the user. The way this file is downloaded is:

1.
FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath(filena me));
2.
if (file.Exists)
3.
{
4.
HttpContext.Current.Response.Clear();
5.
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
6.
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
7.

8.
HttpContext.Current.Response.ContentType = Constants.MimeTypes.Excel;
9.

10.
HttpContext.Current.Response.BufferOutput = true;
11.
HttpContext.Current.Response.WriteFile(file.FullNa me);
12.
HttpContext.Current.Response.End();
13.
}



This works perfectly under IE7, but in Firefox it only works the first time, all subsequent postbacks (downloads or any other postback) is ignored and nothing happens. I guess it must be messing something up in the headers, but can't figure out what's wrong. Any ideas?
If similar code is executed upon url request (ie http://mywebsite/getfile.aspx?id=3) then it works fine, seems it's only when done in a postback.

Thanks very much
Title: Error as Script Time Out.   
Name: Yatish Shah
Date: 11/13/2007 7:50:44 AM
Comment:
While downloading xl sheet from asp pages i am getting following error:
Script Time Out.

I have increased the Script Time Out number.
But still getting the same error.
Should i increase the Download option of Excel sheet from by default 4mb to more. How can i do this?
Please help.
Title: Downloading Files - Forcing the File Download Dialog   
Name: Arvind
Date: 11/2/2007 5:55:29 AM
Comment:
Need more in detail.
Title: IE 6.0 problem - answer...   
Name: Leo
Date: 10/25/2007 10:23:57 AM
Comment:
Response.ContentType = zstrContentType
Response.AppendHeader("Content-Length", zlngFileSize)
'Setting sort of encoding
Response.AppendHeader("Content-Transfer-Encoding", "binary")
Response.AppendHeader("Content-disposition", String.Format("attachment; filename=""{0}""", pstrFileName))
Response.Expires = 0
Response.AppendHeader("Pragma", "cache")
Response.AppendHeader("Cache-control", "private")

This code works perfect in IE 6 (SP2) and IE 7 as well as mozilla browsers. Although it does not work with IE 6 (SP1).
Title: IE 6.0 problem   
Name: Leo
Date: 10/25/2007 9:33:49 AM
Comment:
Same issuse... This code works in all browsers except for IE 6. Can you please help me?.

Response.ContentType = zstrContentType Response.AppendHeader("Content-disposition", String.Format("attachment; filename=""{0}""", pstrFileName))
Response.AppendHeader("Pragma", "public")
Response.AppendHeader("Cache-control", "must-revalidate")

lozano.leonardo@yahoo.com
Title: urgent requirement   
Name: P.Naresh
Date: 10/24/2007 2:07:04 AM
Comment:
Hi
I need this urgently, can any one help me.I need to open a word document from browser which i am doing successfully, but how can i edit it and save it in the same location without prompt dialog, the document is opening in readonly mode.i am using PHP.
Kindly send me the source for this.
Thanks
Title: Excellent work   
Name: bala_tv
Date: 10/16/2007 3:21:29 AM
Comment:
thanks

This is solve my problems
Title: problem with OPEN button   
Name: Mamta
Date: 8/28/2007 3:31:08 AM
Comment:
the "OPEN" button is not opening the file in IE 6.0.Can you please tell y is it happening like that? my email id is mamta.melwani@hcl.in;
Title: need help: urgent   
Name: Meenakshi
Date: 7/27/2007 3:12:38 AM
Comment:
Cord worked very fine. Was able to save it on my local machine. I need to retrieve the values of aspx page(from where the save dialog was opened) onto word doc before saving..
can also be contacted on meenakshi@marineinfratech.com
Title: Downloading a file from sub root folder   
Name: Naveen Kumar Koppera...mumbai
Date: 7/11/2007 10:22:05 AM
Comment:
Hi ,
This code works well but only at root level.ie Appliaction Root.but i want to use Application root/folder level.
i tried to this but you are using relative path.so plz help me how should i download file from subroot level folder
Title: Problems while downloading the PDF files from site   
Name: Avadhut
Date: 7/5/2007 2:14:28 AM
Comment:
Hi All,

I have an application which is used to publish some PDF documents and user (available thru web) will be either opening them for viewing purpose or will save them and then open it.

Recently i added 'content-disposition' header with an intention of providing a proper file name at the time of saving the file.

Now the new problem that i m facing is that when i clik on the document link for some of the PDF files i get 'File Download' dialog box. If i click on 'Open' button it opens it in new Acrobat Window. I m not sure why this change in behavior is thr. This dialog box comes only with IE and not with Firefox.

Also one more observation is that this dialog box comes mostly for PDF files which i have uploaded by downloading from the internet.

If any body has any suggestion's on how to get rid of this 'File Download' dialog box..pls do write.

Advanced Thanks,
Avadhut.
Title: Needs to save the document without prompt   
Name: prashanth
Date: 6/8/2007 7:34:50 AM
Comment:
Hi
I need to open a word document from browser which i am doing successfully, but how can i edit it and save it in the same location without prompt dialog, the document is opening in readonly mode.
Kindly send me the source for this.
Thanks

Prashanth.N
prashanthkumar.n@tcs.com
Title: Not allowing "." in the file name to be downloaded.   
Name: Sajid
Date: 6/5/2007 7:08:18 AM
Comment:
Hi,

Let say i have the code
...
...
1. Response.ContentType = "Application/txt";
2. string FilePath = MapPath("file.txt");
3. Response.AddHeader("Content-Disposition", "attachment; filename=" + "file.txt");
4. Response.WriteFile(FilePath);
5. Response.End();

With this code i can download the file "file.txt";

If i would like to save the file as "file.abc.txt" how can we do it.

I tried with the following code
3. Response.AddHeader("Content-Disposition", "attachment; filename=" + "file.abc.txt");

I can able to download the file but the file name is
"file[1].abc.txt". How can i restrict the "[1]" subscript from the file name.

Please send me your suggessions @: mmsajid@gmail.com

Thanks
Sajid
Title: Mr   
Name: Duc Dinh Nguyen
Date: 5/18/2007 7:38:22 AM
Comment:
Thank you very much.
I am having some problem in this subject.
You are great!
Title: avoid the Filedownload dialog Box   
Name: Dhinesh
Date: 5/14/2007 5:13:28 AM
Comment:
I want to avoid the Filedownload dialog Box before download the CSV file,Please any one helf me. i am using PHP
Title: Forcing the Filedownload dialog   
Name: Raja
Date: 4/29/2007 10:10:40 AM
Comment:
Hi,
This code saved me almost a day. Thanks for the code buddy.
Title: how to avoid file download popup   
Name: Mani
Date: 4/27/2007 8:49:19 AM
Comment:
In my user screen I have view link, if I click this link it will go to servlet and open one word document. It is opening properly, but while opening the attachment it generate one dialog box like file Open, Save or Cancel button, if I click open after that it is opening the document. But my query is it should not display this dialog box, once I click the link it should open the document automatically using HttpServletResponse. Can any one help me to avoid the pop up window?


Sample Code

// Header (file name) is coming and file download pop-up also coming for below code

response.setContentType("application/msword");
response.setHeader("Content-disposition","attachment; filename=testing.doc");

// File name is not coming and file download pop-up also notcoming for below code

response.setContentType("application/msword");
response.setHeader("Content-disposition","inline; filename=testing.doc");

Please any one can help me?
Title: Thanks   
Name: Reinoud
Date: 4/27/2007 4:47:49 AM
Comment:
Nice one! Easy to use... thanks for the effort
Title: open PDF file within browser with asp.net/c#   
Name: anil sahu
Date: 3/30/2007 6:57:35 AM
Comment:
hi dear..
can any 1 help me ...
how can we browse PDF file ?
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "Application/doc";
try
{
Response.WriteFile(Server.MapPath("/Hammocks/Hammock_Image/aspnet-sample.pdf"));
//Response.WriteFile( MapPath( "" +Request.Params["File"].ToString() ) );
Response.Flush();
Response.Close();
}
catch
{
Response.ClearContent();
}
i have used ..but here SAVE as option is there is there..
means user can read it but don't save ..
how can we do this. hel pm.... ASP
thx in advance
Title: good   
Name: i w'll try it
Date: 3/17/2007 7:53:06 AM
Comment:
thank your effort
Title: very useful for me   
Name: ZweThiHa
Date: 3/12/2007 4:39:03 AM
Comment:
very useful for me... thz GIGA
Title: Need to disable a button after download   
Name: Ahm
Date: 3/7/2007 3:03:20 PM
Comment:
Hi, Nice article, but when I say button1.enabled = true after/before response.end(), it is not working.

Do you have any example that shows button enabling/disabling with response.end()?
Title: Viewing a report in PDF or excel in the browser   
Name: Trupthi
Date: 2/25/2007 3:57:01 AM
Comment:
In my application i when the user clicks a button, the report generated should open up in PDF or excel format in the browser window itself without bringing up the dialog box to open or save the file first.

Please let me know how this is done.
Title: Downloading Files -- Forcing the Download Page   
Name: Aaron
Date: 2/21/2007 12:00:19 PM
Comment:
This does not seem to work on with a Windows2003 server with SP1 installed. How can I make it work?
Title: Mr   
Name: Phillip Knezevich
Date: 1/30/2007 12:14:29 PM
Comment:
Great article, not much around about this on MSDN - quick and easy to use, well done.
Title: downloadfile   
Name: mc
Date: 1/24/2007 4:44:49 AM
Comment:
i was hunting for the download file code for almost a month. thanks to u, i've got wat i wanted.
Title: Down Load File   
Name: Bhushan Deo
Date: 1/16/2007 12:12:30 AM
Comment:
The article is good but when we use Windwos2003 Server and Thin Client node the dowload process doesn't run we face that problem. But when we run same project on server it runs properly. Please give me answer. My email id is
deo_bhushan@yahoo.com
Title: uregent:Two dialogues are opening when using this code   
Name: Lakshmi
Date: 12/22/2006 3:40:42 AM
Comment:
If i use the below code to download the xl sheet format, it is showing two dialogue boxes instead of one

Response.ContentType=Response.AppHeader("content-disposition","attachement;filename="+name);
Response.contentType="Application/vn.ms-excel";
Response.WriteFile(path);
Response.End();


Can you help me on this context

Regards,
Lakshmi
Title: Amazing Article....!!!!   
Name: Asif Ali from Indore, India.
Date: 12/22/2006 2:56:47 AM
Comment:
Great Job Steve Sharrock,

Thanks,
Asif Ali (contactasifali@gmail.com)
Title: some additional features !   
Name: Freddie
Date: 11/30/2006 11:47:13 PM
Comment:
Hi everybody ! great article. i just saw this example about downloading a file/report, that creates the downloadable data 'on the fly', which means that the file is never stored anywhere on the server. The only place it's written to disk, is at the end user's computer.
This means you never have to manage any files, or worry about having your files stored in a secure place etc.
It's available at:

http://www.realistic-code-samples.com/CodeViewer.aspx?projectid=8

It shows the code, provides a live demo and source code download etc...

keep up the good work guys :-)
Title: simply gr8   
Name: Fahad
Date: 11/15/2006 3:10:42 PM
Comment:
Brilliant stuff, keep posting...
Title: Download Dialog in Web Application   
Name: sachin from Mumbai
Date: 8/28/2006 9:11:51 AM
Comment:
I want a method that how to display the file download dialog(Save) in Web Application using ASP.NET 2.0?Because on my application file size is unlimited.My application for FTP.File comes from FTP.I have stuck on how to display the download dialog(save) on client machine, and file size is unlimited.
Please help.
Title: Downloading Files   
Name: Saravan Pandian. P(Melss Automation Ltd)
Date: 8/26/2006 3:34:08 AM
Comment:
this artical very supper. realy it is very helpful for me.
i done succfully.

Thanks & Ragards
Title: Problem of "open" in IE   
Name: vijesh
Date: 8/11/2006 5:37:31 AM
Comment:
This code completely works for me. But there is problem the "OPEN" button is not opening the file in IE 6.0 but it works smoothly for mozilla (fire fox) can you just say what is going wrong with IE. My email address is jay_vijesh@rediffmail.com
Please do send reply for this.
Thanks
vijesh
Title: Problem of "open" in IE   
Name: vijesh
Date: 8/11/2006 5:35:49 AM
Comment:
This code completely works for me. But there is problem the "OPEN" button is opening the file in IE 6.0 but it works smoothly for mozilla (fire fox) can you just say what is going wrong with IE. My email address is jay_vijesh@rediffmail.com
Please do send reply for this.
Thanks
vijesh
Title: very nice   
Name: sreekanthreddy kurri
Date: 7/27/2006 7:09:52 AM
Comment:
it is simply super ,& thanks
Title: Remote files   
Name: Ihab El-Kabary
Date: 7/8/2006 8:13:45 AM
Comment:
Excellent article,

I have a problem though, I need to force the SaveFile dialog to download content that is "NOT" on my server. In other words, the files to be downloaded are on other servers.

This code doesnloads only few bytes of files then terminates!

Any ideas??

THANKS

my email is:
ihabmc18@hotmail.com
Title: Mr   
Name: Guillaume
Date: 7/5/2006 9:14:45 AM
Comment:
good code, but I had to change path.GetFullPath(fname) to server.MapPath in order to make everything work with my pages.
Title: File Download Dailg Box   
Name: Preethi Rajesh
Date: 6/6/2006 3:01:11 AM
Comment:
Excellent article, perfect content for file downloading

Thanks
Title: source code to convert ECG text data to dicom format   
Name: awad bakr
Date: 5/14/2006 6:49:41 AM
Comment:
i want source code to convert ECG text data to dicom format
Title: Downloading Files from a Popup window, it itself get closed   
Name: Kirti
Date: 4/25/2006 2:37:27 AM
Comment:
I m trying to download the files from the popup window. it shows me open, save & cncel button. but when I click on cancel. it closes the popup window. I fcaed this issue only on XP. it works fine on win2k/NT.

Please help me out.I m pulling hair out because of this.
Title: Good Article   
Name: Prenesh Seethal (South Africa)
Date: 4/13/2006 4:44:34 AM
Comment:
Is a very good article but entire code should be made available
Title: Mr   
Name: Prenesh
Date: 4/13/2006 4:42:16 AM
Comment:
Is a very good article but entire code should be made available
Title: Solution is Not Working   
Name: Chandan
Date: 4/8/2006 12:30:43 AM
Comment:
Dear Sir,
I want to give option of attachment downloading to user. for that i have to show user file download dialog box how to do that?

waiting for reply
chandan
Title: Nice and easy   
Name: Marcus Pereira
Date: 4/7/2006 9:57:37 AM
Comment:
It was nice to see an easy "how-to" about this issue. I was not interested in wasting my time with this issue, and this article was exactly what I want.
Title: Download File of any Type   
Name: Dilip Singh Bat
Date: 4/7/2006 3:21:52 AM
Comment:
I got the exact solution what i am searching for. It is really simple and short solution. I like this article very much. But Can we build our own window instead of micresoft window.
Title: Save as Dialog   
Name: George Stylli London
Date: 3/31/2006 2:51:42 AM
Comment:
Thanks for the code, searched high and low for this one. Really pleased to get it working.

Thanks for your efforts!!!
Title: Outstanding   
Name: Dean Colcott
Date: 3/21/2006 7:06:50 PM
Comment:
Hi Steve / Mike,

One area not covered was the usefulness this simple few lines of code is in adding security. By setting the file path to a Secure Path (Outside the virtual directory) and having a Adding a key under AppSettings of the web.config you can allow users to download files from a NTFS secured area (Using either the LocalServices or ASPNET user).

Compared to adding a direct link to the file which is not an option when (as in most cases) the download directory is shared by more than one user. In this example use ASP.NET authentication and roles to grant access to the front end and keep your files out of expensive binary store as in SQL / MySQL.

Great work guys. You saved me many headaches.

Regards,

Dean.
Title: Downloading Files - Forcing the File Download Dialog   
Name: ganesh
Date: 2/22/2006 7:24:08 AM
Comment:
This article looks good, but I want to export image file(.jpg) into msword,excel and html.But it was not exporting.
Image file is in server system.
Title: Downloading without dialog   
Name: Roopa
Date: 1/27/2006 8:18:44 AM
Comment:
Can i download a file without prompting the user to save or open the file
Title: How to avoid save file dialog box   
Name: Gary
Date: 1/24/2006 12:09:53 AM
Comment:
How to avoid save file dialog box when i need to save a file automatically?
Title: forcing download dialog box   
Name: captain sportster
Date: 1/14/2006 10:33:28 AM
Comment:
This is exactly what I want to do but I don't want to (can't) use and ASP page. Is there a way to accomplkish this using Javascript in an html page?
Title: Amernath   
Name: Amernath
Date: 9/9/2005 3:09:45 AM
Comment:
Grt code. We even tried out executing it from a popup and it came out successful. Pu an iFrame in the popup and perform the action from it. The iFrame ought to be invisible.This does the trick.
Title: [Continued....]csv files gets appended with .aspx extension in netscape   
Name: Aseem
Date: 9/1/2005 7:09:39 AM
Comment:
context.Response.AddHeader("content-disposition", "attachment;filename=" & fname)
End If
context.Response.BinaryWrite(byteArray)
context.Response.Flush()
context.Response.End()
End If
Catch ex As Exception
Select Case ex.Message
Case "Thread was being aborted."
'do nothing aborted by Response.End()
Case Else
Server.Transfer("error.aspx")
End Select
End Try
****************************

Please let me know how can i avoid getting the ".aspx" appended to the .csv file.
Regards
Aseem
End Sub
Title: csv files gets appended with .aspx extension in netscape   
Name: Aseem
Date: 9/1/2005 7:04:13 AM
Comment:
I am using the following function to download a csv file, but the open file dialog in NS 7.0/7.1 (on win 2k/xp) appends .aspx extension to the file.

*************************************

Public Sub DownloadFile(ByVal fs As MemoryStream, ByVal fname As String, ByVal FileExt As String, ByVal forceDownload As Boolean)

Try

Dim type As String = ""
Select Case FileExt
Case ".htm", ".html"
type = "text/HTML"
Case ".txt"
type = "text/plain"
Case ".doc", ".rtf"
type = "Application/msword"
Case ".csv", ".xls"
'type = "Application/x-msexcel"
type = "text/csv"
Case Else
type = "application/octet-stream"
End Select

If (forceDownload) Then
Dim objCaps As New HttpBrowserCapabilities
objCaps = context.Request.Browser
Dim byteArray As Byte() = fs.ToArray()
context.Response.ClearContent()
context.Response.ClearHeaders()
context.Response.Expires = 0

If objCaps.Browser = "IE" Then
'Checked if OS is WIN XP or MacPC then download as attachment
If UCase(objCaps.Platform.ToString) = UCase("WINXP") Or objCaps.Platform.ToString.StartsWith("M") Then
context.Response.ContentType = type
context.Response.AddHeader("content-disposition", "attachment;filename=" & fname)
Else
context.Response.ContentType = type
context.Response.AddHeader("content-disposition", "inline;filename=" & fname)
End If
Else
context.Response.ContentType = type
context.Response.AddHeader("content-dispositi
Title: Uploading Files   
Name: Ramasamy
Date: 8/30/2005 10:16:20 AM
Comment:
I need a coding in asp.net for uploading a folder to Server.
Let it be clear . I have a button when i click the button i need to ask for browsing a folder in client machine(Folder browser should open not file Browser). If i select a Folder path all the folder files should save in Some Static path directory in Server machine..
Can u please send this coding to me...

please send the response to
ramasamy.p@gmail.com
Title: On-demand PDF creation and download issue   
Name: Michael Yuan
Date: 6/29/2005 11:30:26 AM
Comment:
Hi did anyone find a solution to Girish Nair's problem? i'm interested in the solution, if so you can email me at myuan@anl.com thanks .
Title: very useful article   
Name: Neelesh Arora employee of, www.bbspl.com
Date: 6/21/2005 4:21:29 AM
Comment:
thanks a lot for this code, it helps me to sort out the very big problem. Thanks
Title: How to open/save two files from web server on single click event   
Name: Pinkesh Dalal
Date: 5/27/2005 1:07:25 AM
Comment:
This solution is really good. It helped me to open/save file in asp.net.
Actually i m dealing with images of .bmp and .dcm (DICOM)
I have some other requirement like

"How to open/save two files from web server on single click event in same/different instances of viewer"

I have tried following code but it is opening first file only :
Response.ContentType = "application/x-msdownload"
Response.AddHeader("content-disposition", "attachment; filename=" + filename)
Response.WriteFile(url)

Response.ContentType = "application/x-msdownload"
Response.AddHeader("content-disposition", "attachment; filename=" + filename1)
Response.WriteFile(url1)

Response.flush()
Response.end()

Please be needful for this
Title: On-demand PDF creation and download issue   
Name: Girish Nair
Date: 4/25/2005 12:44:56 PM
Comment:
Sorry, part of the code didn't make it last time. Looks like there is a limit.
private void ExportReport(string strReportId, string strFormatId)
{
Response.Clear();
Response.ClearContent();
Response.BufferOutput = true;
Response.Buffer = true;
int iReportId = Convert.ToInt32(strReportId);
Report selReport = m_RFManager.GetReport(iReportId);
if (selReport == null)
{
Response.End();
}

// Let's start with letting the client(browser) know that we are in the
// process of a file download. This is needed because the report
// generation can take a while and we don't want the user to
// wait for the file download dialog.
string strFileExtension = m_RFManager.GetExportFormatFileExtension(strFormatId);
Response.ContentType = "application/x-download";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + selReport.Name + "."
+ strFileExtension);
Response.Flush();

// Now generate the actual report and send to the client(browser)
byte[] report = m_RFManager.ExportReport(
strReportId,
strFormatId,
ref strFileExtension);

Response.BinaryWrite(report);
Response.Flush();
Response.Close();
// Response.End();
}
Title: On-demand PDF creation and download issue   
Name: Girish Nair
Date: 4/25/2005 12:42:17 PM
Comment:
Folks, I'm struggling with the below issue:
I'm working on the export mechanism for reports dynamically (on-demand) generated using MS SQL Server Reporting Services.
- User via the web interface clicks a button to export to PDF
- My code asks reporting services to create the report in PDF format
- Once the reporting services call (Render() method) returns I write the report as binary to the Response object.

The problem here is that the report generation and PDF creation can take several minutes because of the volume of enterprise-wide data we need to process to create the report that can have 100 to 200 pages. The open/save dialog is currently appearing only after the whole thing (report generation and PDF creating) is over and I don't want my users to wait for minutes before they see the dialog. What I want to do is to force the open/save dialog upfront so that the user can choose one of the options and proceed with other things in the product while download is in progress.
I tried calling Response.Flush() after as follows before I call the actual report creation method, but that doesn't work. It would be awesome if someone can help me out.
Thanks
private void ExportReport(string strReportId, string strFormatId)
{
Response.Clear();
Response.ClearContent();
Response.BufferOutput = true;
Response.Buffer = true;
int iReportId = Convert.ToInt32(strReportId);
Report selReport = m_RFManager.GetReport(iReportId);
if (selReport == null)
{
Response.End();
}

// Let's start with letting the client(browser) know that we are in the
// process of a file download. This is needed because the report
// generation can take a while and we don't want the user to
// wait for the file download dialog.
string strFileExtension = m_RFManager.GetExportFormatFileExtension(strFormatId);
Response.ContentType = "application/x-download";
Response.AppendHeader("Content-Disposition", "attachment;
Title: Excellent   
Name: Sadat Akbar
Date: 4/20/2005 4:07:33 PM
Comment:
It is really a simple but extremly helpfull article for every one keep writting like this way by using simple examples.
Title: how can download pdf file   
Name: gautam bharti
Date: 4/15/2005 5:08:05 PM
Comment:
sir
pl send me code how can i download pdf file in asp.net
gautam.bharti@gmail.com
gautam.bharti@rediffmail.com
Title: how can download pdf file   
Name: gautam bharti
Date: 4/15/2005 5:03:37 PM
Comment:
sir
pl send me code how can i download pdf file in asp.net
Title: Blank browser displayed after clicking save   
Name: amy
Date: 4/15/2005 8:29:21 AM
Comment:
\
Title: Misbeahvior   
Name: Petar
Date: 4/14/2005 4:24:44 AM
Comment:
am i the only one who experience strange misbehave with asp.net download via response object!?
when i use the code above my page from which the request has came FREEZE. I mean each postback to the server is the same request for download the file. Whatever i click on the page it starts downloading the file again. Has anyone experienced it!?? please mail me at: pip010@mail.bg
Title: File DownLoad   
Name: Anthoniz Raemsh
Date: 3/29/2005 6:52:43 AM
Comment:
This article is very useful for me but I want to find out if we can take this a step further. What I
mean by this is, can we find out if the user clicked "Open" or "Save" or "Cancel" buttons on the fi
le download dialog? Is there a handle that I returned with the what the user clicked. I'm more inter
ested to know if the user clicked cancel button. I need to do specific action if the user clicks can
cel button or the save button. Please help me. Thanks a ton. If you know the answer (or any ideas) p
lease email me at ramesha@hexaware.com. Thanks. Ramaa
Title: please help me   
Name: Hardik
Date: 3/12/2005 6:43:27 AM
Comment:
Hi,
I have seen this article it is really very nice. But i want that when i click on a particular button a report is generated in excel format automatically taking data from ms access and it just prompts me to save it. I dont want to display the report. So is it possible through ASP if yes then please describe me how can it be.
My mail id is hardik_bhatt@indiatimes.com..
plz reply back me as soon as possible..
its urgent.......

regards,
hardik
Title: download code   
Name: sirisha
Date: 3/4/2005 5:17:15 AM
Comment:
can you give the code for asp
Title: Download OK! But Open FAILS.....   
Name: Joe
Date: 1/17/2005 4:28:20 PM
Comment:
Hi
Selecting "download" on Document Download Dialog Box runs OK.
But selecting "open" (after saving to temp folder) fails
on IE 6. No Problem on Mozilla.
Any suggestions???
Title: Download Problem (Cont...)   
Name: Vikas Patwal
Date: 1/6/2005 4:22:34 AM
Comment:
I am trying to download the music file...
here is rest of the code:

ElseIf Trim(UCase(strFileExtname)) = UCase("avi") Then
Response.ContentType = "video/x-msvideo"
ElseIf Trim(UCase(strFileExtname)) = UCase("movie") Then
Response.ContentType = "video/x-sgi-movie"
Else
Response.ContentType = "application/octet-stream"
End If
End If
End If
Response.AddHeader("Content-Disposition", "attachment; filename=""" & StrFileName & """")
'Response.AppendHeader("Content-Disposition", "attachment; filename=""" & StrFileName & """")
Response.Flush()
Response.WriteFile(pStrFile)
Response.ClearHeaders()
Title: Downloding Problem   
Name: Vikas Patwal
Date: 1/6/2005 4:20:42 AM
Comment:
Hi,

By using almost same code around 80% time I am able to download the and sometimes I am getting problem.

Problem is that I am not getting the full download.

It shows download complete but downloads only some bytes and sometimes 0 bytes. Can anybody give me the solution for this. My code is as follows:

strFileExt = Split(StrFileName, ".")
If UBound(strFileExt) > 0 Then
strFileExtname = strFileExt(UBound(strFileExt))
If Trim(UCase(strFileExtname)) = UCase("au") Or Trim(UCase(strFileExtname)) = UCase("snd") Then
Response.ContentType = "audio/basic"
ElseIf Trim(UCase(strFileExtname)) = UCase("mid") Or Trim(UCase(strFileExtname)) = UCase("midi") Then
Response.ContentType = "audio/midi"
ElseIf Trim(UCase(strFileExtname)) = UCase("mpga") Or Trim(UCase(strFileExtname)) = UCase("mp2") Or Trim(UCase(strFileExtname)) = UCase("mp3") Then
Response.ContentType = "audio/mpeg"
ElseIf Trim(UCase(strFileExtname)) = UCase("aif") Or Trim(UCase(strFileExtname)) = UCase("aiff") Or Trim(UCase(strFileExtname)) = UCase("aifc") Then
Response.ContentType = "audio/x-aiff"
ElseIf Trim(UCase(strFileExtname)) = UCase("ram") Or Trim(UCase(strFileExtname)) = UCase("rm") Then
Response.ContentType = "audio/x-pn-realaudio"
ElseIf Trim(UCase(strFileExtname)) = UCase("rpm") Then
Response.ContentType = "audio/x-pn-realaudio-plugin"
ElseIf Trim(UCase(strFileExtname)) = UCase("ra") Then
Response.ContentType = "audio/x-realaudio"
ElseIf Trim(UCase(strFileExtname)) = UCase("wav") Then
Response.ContentType = "audio/x-wav"
ElseIf Trim(UCase(strFileExtname)) = UCase("mpeg") Or Trim(UCase(strFileExtname)) = UCase("mpg") Or Trim(UCase(strFileExtname)) = UCase("mpe") Then
Response.ContentType = "video/mpeg"
ElseIf Trim(UCase(strFileExtname)) = UCase("qt") Or Trim(UCase(strFileExtname)) = UCase("mov") Then
Response.ContentType = "video/quicktime"
ElseIf Trim(UCase(strFi
Title: u the man   
Name: ste
Date: 12/20/2004 10:50:15 PM
Comment:
u the man
Title: Great Article   
Name: David Ray
Date: 12/15/2004 11:30:13 AM
Comment:
Would love to know if there's a way to achieve the same effect via client-side scripting. Often, I won't have access to the server, but would love to embed this on a per page basis. Any ideas?

Thanks,
DR ;-}
Title: Downloading without Dialog   
Name: Glenn Rosenthal
Date: 11/23/2004 4:56:15 PM
Comment:
This article looks great. However, I want to be able to download files from the server to a specific local path and name, without prompting the user. Is this possible?
Title: Downloading Files from a Popup window is closing itself   
Name: Gina
Date: 11/8/2004 5:14:06 PM
Comment:
Thanks for this!

It works great except for when I want to use it from within a popup. If I use the above code from within a popup, the file Dialog box is displayed properly, but when I click save, it closes the Popup window that called it. Any idea how to stop that?! I'm pulling my hair out!
Title: very good article   
Name: veera reddy
Date: 11/4/2004 1:10:10 AM
Comment:
this is really a fantastic article. it gives nitty-gritty details about file downloading in asp.net i would like to say thanks to steve sharrock and mike .
Title: Thanks!! This was very helpful!!   
Name: Hemanshu Shah
Date: 11/1/2004 6:42:06 AM
Comment:
I wanted this solution from very very long time. Thanks for posting this article.

Just this much code works great,

Response.ContentType = "application/x-msdownload";
Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
Response.WriteFile(strLocalFile);

Content Type and the Content Disposition does the great magic for which i could not find any documentation earlier.

Regards,
Hemanshu
Title: How to display Chinese in the File Download (save) dialog?   
Name: minsun_y
Date: 8/5/2004 9:09:15 AM
Comment:
I want a method that how to display the filename in Chinese in the File Download (save) dialog?Because on my test,the filename can't corrected display.And,Can I find out if the user clicked "Open" or "Save" or "Cancel" buttons on the fi
le download dialog?
Title: Downloading Files - Forcing the File Download Dialog - taking this a step further.   
Name: Ramaa
Date: 7/8/2004 9:45:13 AM
Comment:
This article is very useful for me but I want to find out if we can take this a step further. What I mean by this is, can we find out if the user clicked "Open" or "Save" or "Cancel" buttons on the file download dialog? Is there a handle that I returned with the what the user clicked. I'm more interested to know if the user clicked cancel button. I need to do specific action if the user clicks cancel button or the save button. Please help me. Thanks a ton. If you know the answer (or any ideas) please email me at rum23@hotmail.com. Thanks. Ramaa
Title: Downloading Files -- Forcing the Download Page   
Name: 'lil Mikey from Andomeda Tennessee
Date: 7/7/2004 11:43:23 AM
Comment:
Mike Harber's code snippet was the first really complete example out of thousands. His thoroughness ended a long arduous quest. Pour me a tall one general, I'm a comin' home.

Product Spotlight
Product Spotlight 






Ads Powered by Lake Quincy Media
Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2008 ASPAlliance.com  |  Page Processed at 5/9/2008 5:54:58 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search