Downloading a File with a Save As Dialog in ASP.NET
Here is a common question that I hear frequently: "How do I download a file from a Web site, but instead of displaying it in the browser see it as a file that can be saved (ie. see the Save As dialog)?"
Response.AppendHeader("Content-Disposition", "attachment; filename=SailBig.jpg");
Normally, when you link a file that file will always display inside of the browser because the browser loads it and automatically determines the content type based on the file extension. The Web Server provides a content type based on mime-type mappings, and based on that content type the browser serves the page and displays it.
So when you click on a link like a jpg image the browser knows it's an image and will display that image. You can of course always use the browser short cut menu and use the Save Target As option to save the file to disk.
The Content-Disposition Header
The key element to allow a file to be treated as a file rather than content to be displayed in the browser is the Content-Disposition header.
The Content-Disposition header basically allows you to specify that the response you're sending back is to be treated as an attachment rather than content which results in the download dialog.
In ASP.NET you can add the Content-Disposition header like this:
Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition", "attachment; filename=SailBig.jpg");
Response.TransmitFile(Server.MapPath("~/images/sailbig.jpg"));
Response.End();
You specify that the output is an attachment and the name that is to be displayed on the download dialog (or the actual downloaded file if auto-download is used).
Here's what this dialog looks like in FireFox when you specify a Content-Disposition header:
Note that this behavior varies from browser to browser though. Firefox has this nice dialog that gives you choices. Internet Explorer shows the yellow bottom bar asking whether you want to save the file. Chrome - depending on the options - will simply download the file to your Downloads folder without prompting for anything.
Sending a Binary File to the Client
If you want to force a Save As dialog automatically when a link is clicked via code from the server side, you have to send the file back through code using Response.TransmitFile(), Response.BinaryWrite() or streaming it into the Response.OutputStream and add a couple of custom headers to the output.
The optimal way to do this is to use Response.TransmitFile() to explicitly send the file from your ASP.NET application and then add the Content Type and Content-Disposition headers. Note thought that Response.TransmitFile() in recent versions of IIS can only serve files out of the virtual folder hierarchy of the Web site or virtual. For files outside of the virtual path you have to stream into the OutputStream().
Assuming your file does live inside of the folder hierarchy here's how you can force the Save As dialog for output sent with TransmitFile():
Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition", "attachment; filename=SailBig.jpg");
Response.TransmitFile(Server.MapPath("~/images/sailbig.jpg"));
Response.End();
This will cause a Open / Save As dialog box to pop up with the filename of SailBig.jpg as the default filename preset.
Can't use TransmitFile?
The previous example used TransmitFile() which is most efficient, but you don't always have files to work with or you may have files that live outside of the directory structure of your Web site which TransmitFile() doesn't allow for. Luckily there are other ways to send binary data to the client from ASP.NET code.
To write binary data that is a byte[] you can use the Response.BinaryWrite() method to write out binary data. If you have a Stream of binary data, you can stream the data directly into the into the Response.OutputStream.
Here's an example of streaming an image directly into the Response.OutputStream from a Bitmap:
Bitmap bmp = ImageUtils.CornerImage(); // retrieve an image
Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition", "attachment; filename=LeftCorner.jpg");
bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
This code simply uses the bmp.Save() method which writes a binary stream into the Response.OutputStream which results in the binary data being sent to the client. Any Stream features (like Stream.Copy) behaviors can be applied to the OutputStream to stream data to the client.
If you're dealing with files, try to avoid streams if you can and use TransmitFile() instead. TransmitFile is very efficient because it offloads the file streaming to IIS which happens off an I/O port so the file streaming releases the IIS request thread while returning the file. This is especially useful when streaming large files to the client as it doesn't tie up the IIS pipeline.
Saving rather than Viewing
Browsers are focused on displaying content within the browser's viewport. When you do need to download content rather than view Content-Disposition is your friend… I hope you found this short post useful.
Other Posts you might also like
The Voices of Reason
# re: Downloading a File with a Save As Dialog in ASP.NET
http://www.west-wind.com/WebLog/posts/8230.aspx
# re: Downloading a File with a Save As Dialog in ASP.NET
Response.ContentType = "application/octet-stream";
This should (at least in my experience) open Save dialog. I blogged here about it here (http://geekswithblogs.net/rachit/archive/2007/04/25/How-to-Download-file-from-ASP.Net-2.0-Page.aspx)
# re: Downloading a File with a Save As Dialog in ASP.NET
Rick - thanks a bunch for pointing out the efficiency of TransmitFile()! I have never heard of it, and now I am changing several in-production implementations to reflect your suggestions. Historically, I have always used the WriteFile() method (and to think... I have been buffering data unnecessarily).
Thanks again!
# re: Downloading a File with a Save As Dialog in ASP.NET
Keep up the good work, cheers,
Andreas
# re: Downloading a File with a Save As Dialog in ASP.NET
If the filename contains non-english characters, ie6/ie7 mess up the file name in the save as dialog. No such problem in firefox.
So I need to "hack" the file name for ie...
# Supporting resume
An extension to this idea would be to override the DefaultHttpHandler, and add content-disposition on all URLs that ended with ?download=true. This would give the requesting page control over whether the jpeg/mp3/etc should be displayed or downloaded, wouldn't circumvent the authorization system like many download.aspx?filename=web.config systems do, and wouldnt' display files that are forbidden or are scripts.
Do you know of a HttpHandler like the one in the MSDN article that uses TransmitFile instead, and is well-tested?
Thanks,
Nathanael
# re: Downloading a File with a Save As Dialog in ASP.NET
One simple question. If we have multiple downloadable files, how would we handle the AppendHeader & TransmitFile methods. Also if the files are from the database, how do we use the TransmitFile method.
Besides, you are one of the top .NET Experts around and on this site i find articles of great value found no where else. You really give us the true insight on different issues. Thumbs upto you.
Regards...
# re: Downloading a File with a Save As Dialog in ASP.NET
Thanks
# re: Downloading a File with a Save As Dialog in ASP.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim doc As XmlDocument = New XmlDocument() doc.LoadXml("<book category=""COOKING""> <title lang=""en"">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price></book>") Response.ContentType = "text/plain" Response.AppendHeader("Content-Disposition", "attachment; filename=test.xml") doc.Save(Response.OutputStream) End Sub
But when I run the application I am getting the xml document appended ontop of the html response as follows:
<book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head><title> Untitled Page </title></head> <body> <form name="form1" method="post" action="Default.aspx" id="form1"> <div> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNzgzNDMwNTMzZGTv6WZRVQFjnUdILutXPVpxX0nm4w==" /> </div> <div> </div> </form> </body> </html>
I would really appreciate if you could help me.
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
Thank you very much!
# re: Downloading a File with a Save As Dialog in ASP.NET
Great work Rick!!!!!
I am trying to write a page that enables user to download a dynamically generated word document. The doc is generated based on a template word document, so i have certain format settings (ex - bolds and italics) and images in this word document that i don't wanna loose.
i don't wanna save this doc in the server and then do a Response.Transmit() or a Response.WriteFile(). how can i allow this dynamically generated document to be allowed to be saved with all its format info?
# re: Downloading a File with a Save As Dialog in ASP.NET
Response.BinaryWrite()
or if you have the output in a stream write to the ResponseStream as shown in the post.
# re: Downloading a File with a Save As Dialog in ASP.NET
I need to open the file in a new window, show the open save cancel dialog box and then close the window when the user chooses an option. Is there any way to do That
# re: Downloading a File with a Save As Dialog in ASP.NET
is there any handle for dialouge box?
In our application we want to perform certain operation based on user action on file dialouge box. E.g We are providing option to download database records in CSV file and after successful SAVE of the .CSV file we want to delete the downloaded records. If user clicks on Cancel button we don't want to perform any DB operation.
# re: Downloading a File with a Save As Dialog in ASP.NET
What you can do if you're dealing with CSV files is use AJAX to load the data into the browser as a string, parse it and deal with it there then get rid of the data, but this obviously only works with text data and only if you can actually parse this data on the client.
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
Great thread.
I am trying to save an excel file. And it works fine with
Response.ContentType = "application/ms-excel"; Response.AddHeader("content-disposition", "inline; filename=Records.xls"); Response.TransmitFile(randomFileName); Response.Flush();
But my requirement is to download multiple excel files on button click. I tried this in various ways. Nothing seems to help. Only the first one gets downloaded. Would you be able to suggest?
Rgds
Sandeep
# re: Downloading a File with a Save As Dialog in ASP.NET
If you need to return multiple files you should zip them and send the compound Zip file back to the client instead.
# re: Downloading a File with a Save As Dialog in ASP.NET
I tried a workaround
On click of a button, call a javascript function to loop say 5 times and call the button_click serverside event.
But it didn't work. I guess when the page is doing a postback, it stops execution of the javascript.
I have another dirty workaround (if popups are allowed). Open say 5 popups. And onload of each of them, download a file. Of course the user has the irritating duty of clicking on save for each of them.
# re: Downloading a File with a Save As Dialog in ASP.NET
Very useful article. It may be a long shot but is there anyway I can capture the file location the user chooses from the save dialog box?
# re: Downloading a File with a Save As Dialog in ASP.NET
In one of my application . Iam trying to dowload the file. I want to display a message on the borwser saying 'Download complete'. But since I change the content type for file download the message doesn't appear on the browser. Is there a way to show the messge on the browser once the download is complete.
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
Great post. I am trying to use this in an UpdatePanel and can't find anyway of getting it to work. It seems as though the use of Response.Write() has been banned from UpdatePanels. Any chance you can give me a fix for the problem?
Thanks,
# re: Downloading a File with a Save As Dialog in ASP.NET
If you want do uploads of files 'independently' of the page, stick the file upload component into an IFRAME and process that separately.
# re: Downloading a File with a Save As Dialog in ASP.NET
this is a good post which is very helpful but i have a problem, on click of a button i have to save an excel file directly on server without showing a dialog box. Also i want to zip multiple file and directly save them on server without giving a dialog box.
Thnks.
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
I wish to perform a silent download of the file in the background without any under interaction.
Any help would be appreciated.
Thanks.
# re: Downloading a File with a Save As Dialog in ASP.NET
You can download and show directly in the browser, a file download dialog or an AJAX type call but you can't write directly to disk.
# re: Downloading a File with a Save As Dialog in ASP.NET
How about opening the file in a new window? What would the syntax be for that? I'm calling a fileviewerBL which calls the fileviewerDL to get the file info.
Dim fs As New FileServiceBL(New DataFactoryDL().GetDatabase(myBusiness_Entity.eConnType.Common)) Dim ContentType As String = String.Empty Dim b As Byte() = fs.Retrieve(myBusiness_Entity.eAttachmentTypes.Report, rptKy, False, Nothing, ContentType) Response.ClearContent() Response.ClearHeaders() Response.AddHeader("Content-Length", b.Length.ToString) Response.ContentType = ContentType Response.BinaryWrite(b) Response.Flush() Response.Clear()
# re: Downloading a File with a Save As Dialog in ASP.NET
ClientScript.RegisterClientScriptBlock(....)
# re: Downloading a File with a Save As Dialog in ASP.NET
I am new to this file upload and download, and I am running into a serious issue here.
My code uploads the file properly, however, when I want to download the file, it seems to be downloading the same file over and over. It's really frustrating! I went through my code thoroughly but I can certainly use a fresh pair of eyes. Here's my code:
this code uploads and downloads the file. Please guys respond as soon as you get the opportunity, Thank you. VB.net 2005
Private Sub fileuploadAttachments()
Dim strName As String
strName = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName)
Dim extension As String = Path.GetExtension(fileUpload.PostedFile.FileName).ToLower()
Dim MIMEType As String = Nothing
Select Case extension
Case ".gif"
MIMEType = "image/gif"
Case ".jpg", ".jpeg", ".jpe"
MIMEType = "image/jpeg"
Case ".png"
MIMEType = "image/png"
Case ".rtf", ".rtx"
MIMEType = "text/richtext"
Case ".txt"
MIMEType = "text/plain"
Case ".zip"
MIMEType = "application/zip"
Case ".pdf"
MIMEType = "application/pdf"
Case ".doc", ".docx"
MIMEType = "application/msword"
Case ".xls"
MIMEType = "application/excel"
Case Else
MIMEType = "application/x-binary"
'Invalid file type uploaded
'MsgBox("Invalid file type to uploaded", MsgBoxStyle.OkOnly, "Invalid file type")
Exit Sub
End Select
Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("BudgetConnectionString").ConnectionString)
Const SQL As String = "INSERT INTO attachments2 (project_id, attachment_name, MIMEType, attachment) VALUES (@project_id,@attachment_name, @MIMEType, @attachment) "
Dim myCommand As New SqlCommand(SQL, myConnection)
Dim fileNamePosted As String = fileUpload.PostedFile.FileName
myCommand.Parameters.AddWithValue("@project_id", Val(lbltempprojID.Text))
myCommand.Parameters.AddWithValue("@attachment_name", strName)
myCommand.Parameters.AddWithValue("@MIMEType", MIMEType)
'Load fileUpload's InputStream into Byte array
Dim imageBytes(fileUpload.PostedFile.InputStream.Length) As Byte
fileUpload.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length)
myCommand.Parameters.AddWithValue("@attachment", imageBytes)
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
End Sub
Private Sub downloadAttachments()
Dim attachProjId As Integer
If Request.QueryString("projID") = "" Then
attachProjId = Val(lbltempprojID.Text)
Else
attachProjId = Request.QueryString("projID")
End If
Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("BudgetConnectionString").ConnectionString)
Const SQL As String = "Select attachment_name, MIMEType, attachment From attachments2 Where attachment_id =@attachment_id "
Dim myCommand As New SqlCommand(SQL, myConnection)
myCommand.Parameters.AddWithValue("@attachment_id", attachID)
myConnection.Open()
Dim myReader As SqlDataReader = myCommand.ExecuteReader
If myReader.Read Then
Response.ContentType = myReader("MIMEType").ToString()
Response.AppendHeader("Content-Disposition", "attachment; FileName=" + myReader("attachment_name").ToString)
Response.BinaryWrite(myReader("attachment"))
End If
myReader.Close()
myConnection.Close()
End Using
End Sub
# re: Downloading a File with a Save As Dialog in ASP.NET
I am (trying to) use this technique to download various file types from a SharePoint page. I have the code in the "SelectedIndexChange" event of a gridview object. The code works the first time you click a link, but then no links (or buttons or anything) work on the page until I do a refresh (F5).
Any thoughts?
Code....
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fi.Name);
Response.AppendHeader("Content-Length", fi.Length.ToString());
Response.ContentType = "application//octet-stream";
Response.TransmitFile(fi.FullName);
Response.Flush();
Response.End();
# re: Downloading a File with a Save As Dialog in ASP.NET
IE caches content type information and so if you have pages that return different content types for the same page don't work right because IE misinterprets the content type of the actual data.
In short you should make sure you serve 'file content' of a unique URL always - either on a separate page/IFrame or if necessary by amending the URL in such a way that it's unique (appending a timestamp to the querystring for example).
# re: Downloading a File with a Save As Dialog in ASP.NET
Great comments and ideas. Very clear.
I tried running this on my local server and works fine. As soon as I put this up onto our live server the result is completely different. I click the save button and I get an error as IE seems to want to open the aspx page again and reports
"Internet Explorer cannot download "my_page.aspx" from ourliveserver."
"The requested site is unavailable or cannot be found. Try again later"
Quite honestly I've spent hours on this and getting nowhere, brain is jelly! I might guess that opening a new page may work but what is the syntax for that?
Any help much appreciated!!
Code:
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=FileName.txt")
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/vnd.text"
Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
Response.Write(str.ToString())
Response.TransmitFile(Server.MapPath("~/FileName.txt"))
Response.End()# re: Downloading a File with a Save As Dialog in ASP.NET
Thanks Rick for this great thread.
One question though, i am programming a 'download' button, so when a user clicks i want that the 'save as' page will pop directly, i.e. eliminate the 'do you want to open or save the file' window, since it is clear that the user wants to download the file.
Thanks again
David
# re: Downloading a File with a Save As Dialog in ASP.NET
@Jeff - I'd guess the problem is that you're writing a file out to disk and probably don't have permissions to do that. There's no reason for you to write to file first anyway. Just use Response.Write() or Response.BinaryWrite() to output your file content and it'll probably work.
# re: Downloading a File with a Save As Dialog in ASP.NET
http://support.microsoft.com/default.aspx?scid=KB;EN-US;q316431
# re: Downloading a File with a Save As Dialog in ASP.NET
I have seen a lot of comments and useful talk here..
i have tried both Response.Transmit and Response.WriteFile.
But...
If there is Resume Support then there are no multiple connections and..
when there are multiple connections there is no resume support..
i want to do Multipart(segmented) Resumeable Downloading in while at the same time hiding my download link..
<code lang="vb"
Public Shared Sub DownloadFile(ByVal FilePath As String, Optional ByVal ContentType As String = "")
If File.Exists(FilePath) Then
Dim myFileInfo As FileInfo
Dim StartPos As Long = 0, FileSize As Long, EndPos As Long
myFileInfo = New FileInfo(FilePath)
FileSize = myFileInfo.Length
EndPos = FileSize
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ClearHeaders()
HttpContext.Current.Response.ClearContent()
Dim Range As String = HttpContext.Current.Request.Headers("Range")
If Not ((Range Is Nothing) Or (Range = "")) Then
Dim StartEnd As Array = Range.SubString(Range.LastIndexOf("=") + 1).Split("-")
If Not StartEnd(0) = "" Then
StartPos = CType(StartEnd(0), Long)
End If
If StartEnd.GetUpperBound(0) >= 1 And Not StartEnd(1) = "" Then
EndPos = CType(StartEnd(1), Long)
Else
EndPos = FileSize - StartPos
End If
If EndPos > FileSize Then
EndPos = FileSize - StartPos
End If
HttpContext.Current.Response.StatusCode = 206
HttpContext.Current.Response.StatusDescription = "Partial Content"
HttpContext.Current.Response.AppendHeader("Content-Range", "bytes " & StartPos & "-" & EndPos & "/" & FileSize)
End If
If Not (ContentType = "") And (StartPos = 0) Then
HttpContext.Current.Response.ContentType = ContentType
End If
Try
HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment; filename=" & myFileInfo.Name)
HttpContext.Current.Response.WriteFile(FilePath, StartPos, EndPos)
HttpContext.Current.Response.End()
Catch Ex As Exception
End Try
End If
End Sub
</code>
# re: Downloading a File with a Save As Dialog in ASP.NET
I don't know how to get a stream representing this handler's output.
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
Can we have just the Save option and not the Open button in the pop up?
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
I have some issue with file download. I want the download to happen without showing the download dialog. I am setting the Content-Disposition to inline. Nothing comes in the screen. A blank screen comes. If i change the inline to attachment, it works by showiung the save dialog. I am using IE7.
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename =test.pdf");
HttpContext.Current.Response.BinaryWrite((byte[])result["InvestorRpt"]);//get data in variable in binary format
HttpContext.Current.Response.End();
IN IE6, this works by showing the save dialog.
Any idea how to show the file without the save dialog
Pls let me know
Sree
# re: Downloading a File with a Save As Dialog in ASP.NET
out via a download.aspx page running in an iframe , I have to get the download to happen from an iframe because the download initiated link comes from a grid that has to complete its
item command event .
# re: Downloading a File with a Save As Dialog in ASP.NET
I am having trouble with Office 2007 files getting corrupted when downloaded using this method.
I tried setting the ContentType to both "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" (in the case of an Excel 2007 file) and "application/octet-stream", but the same result. When I try to open the downloaded file, I am getting an error: "Excel found unreadable content in Workbook".
Any of you guys having trouble using this approach to download Office 2007 files?
Thanks,
Cristi
# re: Downloading a File with a Save As Dialog in ASP.NET
Thanks Rick for these kind of posts, they are very useful.
Cristi
# re: Downloading a File with a Save As Dialog in ASP.NET
I have a web application(ASP.NET 2.0, C#), in which I am exporting a xml file.
The web page has a button called Export. When the user clicks the Export button, the File Download pops up, in which it has the Open,Save and Cancel Butons as in a normal file download pop-up. Being an xml file, the page also opens up,without the content behind the File download pop-up,
When the user clicks Cancel button, the file download pop up is gone, but the xml page(without the contents) is still open. This also happens when the user has successfully downloaded the xml file(Xml page is open)
Is it possible to close the xml page after the user clicks the cancel button and after the user saves the xml file? I am using Internet Explorer 6, Windows xp, SP1.
Please help.. Thanks
# re: Downloading a File with a Save As Dialog in ASP.NET
Response.ContentType = "image/jpeg"
Response.AppendHeader("Content-Disposition", "attachment; filename=" + imgpath)
'Response.Write("imgpath")
'Response.Write(imgpath)
Response.TransmitFile(Server.MapPath(imgpath))
Response.End()
The imgpath variable holds the path of the image..This path is stored in database..
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
Suppose the code below was in a page called generatefile.asp. A process on the server could call generatefile.asp, but then the PDF would open on the server and "prompt" to save or the file would open. Since no one is directly working on the server, no one would be able to click save on the box.
I could remove the mime association for the PDF and retie the file type to a custom application to intercept PDF file types, but my custom application wouldn't know how to interpret the xml since only Adobe would know how to generate the PDF. I can’t just download the http://localhost/test/test.pdf file because it uses the xml in the response to populate the form.
Here is the code in ASP and then below in C#. What this does is that it merges the PDF with the xml to populate the PDF document on the fly.
Code in C#
StringBuilder responseString = new StringBuilder(); Response.ContentType = "application/vnd.adobe.xdp+xml"; responseString.Append("<?xml version='1.0' encoding='UTF-8'?>"); responseString.Append("<?xfa generator='AdobeDesigner_V7.0' APIVersion='2.2.4333.0'?>"); responseString.Append("<xdp:xdp xmlns:xdp='http://ns.adobe.com/xdp/'>"); responseString.Append("<xfa:datasets xmlns:xfa='http://www.xfa.org/schema/xfa-data/1.0/'>"); responseString.Append("<xfa:data>"); responseString.Append("<form1>"); responseString.Append("<TextField1>aaaaaaaa</TextField1>"); responseString.Append("</form1>"); responseString.Append("</xfa:data>"); responseString.Append("</xfa:datasets>"); responseString.Append("<pdf href='http://localhost/test/test.pdf' xmlns='http://ns.adobe.com/xdp/pdf/' />"); responseString.Append("</xdp:xdp>"); Response.Write(responseString); Response.Flush(); Response.End();
Any ideas?
# re: Downloading a File with a Save As Dialog in ASP.NET
This solves my problem and works great. But it only works on my Dev PC. In my production environment, Win2k running network load balancing with 2 web servers, this does not work.
Response.ContentType = "image/jpeg"; Response.AppendHeader("Content-Disposition", "attachment; filename=myfile.jpg" ); Response.TransmitFile(Server.MapPath(lcMyfilePath)); Response.End();
When I press my download button, the browser displays a "Server Application Unavailable". My error routine does NOT log an error, but the event log does log this error:
***********
TransmitFile failed.
File Name: \\mynas\data$\data\images\myimage.jpg,
Impersonation Enabled: 0, Token Valid: 1, HRESULT: 0x8007052e
***********
What cause this problem?
Thanks,
Jerry
# re: Downloading a File with a Save As Dialog in ASP.NET
# Downloading a File with a Save As Dialog in ASP.NET
I had written a code which downloads the file, in the best of manner, now the problem i face is a bit different. After the download is completed, i want to redirect the user to some other page, but it is not possible as we stated
Response.End();
I wanted to know, how to accomplish this task?
# re: Downloading a File with a Save As Dialog in ASP.NET
Still having problems getting Response.TransmitFile() to work in our production webfarm. The image directory is a IIS virtual directory on the NAS server. I can display the images fine in my ASP.Net webform. But the button on this webform that performs the TransmitFile() still causes a the message "Server Application Unavailable".
I even tried hard coding the file name to download into the TransmitFile() function, but this didn't help. Below are two examples, should these two examples work?
Response.ContentType = "image/jpeg"; Response.AppendHeader("Content-Disposition", "attachment; filename=myfile.jpg" ); Response.TransmitFile(Server.MapPath(/Myimages/Subfolder/MyFile.jpg)); //Response.TransmitFile("\\\\MyNasServer\\Data$\\MyImages\\Subfolder1\\Subfolder2\\MyMyFile.jpg"); Response.End();
Anything else I can try or test in order to figure this out?
Thanks,
Jerry
# re: Downloading a File with a Save As Dialog in ASP.NET
How can I check whether the user actually clicked "save" and not "cancel"?
Files can be downloaded fine but I need to write to a Database after the user saves a file but dont want to write to it if they click cancel and dont actually save the file.
Basically something like:
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", "inline; file1.xls");
Response.WriteFile(randomFileName);
If(user clicked cancel)
{
Do nothing
}
else if (user clicked save)
{
write to a database
}
Do you know how I can tell which button they clicked?
Thanks.
# re: Downloading a File with a Save As Dialog in ASP.NET
My app allows users to attach documents and images to various things they're working with. The attachments are displayed in a listbox, user chooses one, and clicks View which runs javascript to pop up my AttachmentViewer.aspx page.
It's a blank page, here's the applicable code for the page:
Response.ContentType = Attachment.ContentType Response.AddHeader("Content-Disposition", _ "attachment; filename=""" & Attachment.FileName & Attachment.FileExt & """") Response.BinaryWrite(Attachment.GetFile)
and javascript:
window.open(""" & String.Concat(Request.ApplicationPath.TrimEnd("/"), "/secure/AttachmentViewer.aspx") & """, ""Attachment"", ""location=0,toolbar=0,menubar=0,directories=0,scrollbars=1,resizable=1"");Nothing else going on really. Attachment is an instance of a class that pulls info and a byte array from the db.
This works as expected in Firefox, but for some reason in IE, the page pops up, beeps at me, and closes. If I change attachment to inline it will display images, but still errors for Office documents.
Something to do with the popup I guess, because I can go to the page in the main window and it's fine. Help?
# re: Downloading a File with a Save As Dialog in ASP.NET
Apparently some IE security feature.
# re: Downloading a File with a Save As Dialog in ASP.NET
I am having strange problem, regarding dialog box, popped for Download.
My downloading code in C# is
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + "."
+ fileType);
Response.BinaryWrite(fileData);
Response.End();
where fileData is binary array.
On my page , I showed fileNames in hyperlink or linkbutton. Now whenever User clicks on them , that file Downloads.
Now problem is that , after downloading, say Open or Save or Cancel operation , if I click any other button without refreshing my Page, same Dialog box Pops up, Suppressing Functionality of that button.
For Example , if i click on ChangeName of File button after any file Download, it will still Show me that Previously opened Download Dialog box.
Any take, why this is happening?
# re: Downloading a File with a Save As Dialog in ASP.NET
Problem posted by me , is occurring because of my foolish mistake. What I did, is that I kept some hidden variables and set values to it , on any FileName to identify whether it is Folder
( So that I can show Folder's explored view.) or document ( in this case document will be downloaded). I checked this hidden field on each PageLoad , whether it has any value or not. Now Why i did this , rather than handling onClick event on ServerSide is long story. I need to do it due to dynamic generation of controls.
Anyways, Now Since, after Each download popup , I Used Response.End();. Thus my Client side HTML is not Refreshed . So , on any next Postback , About said checking always yields true, Same functionality of Showing download popup box executes. Now , I cleared that hidden field on each Postback in javascript , other than above said Click.
# re: Downloading a File with a Save As Dialog in ASP.NET
I have a file of type "application/msword" in sql server image type variable. I want to download this with VB.Net. How is it possible?
# Downloading a File with a Save As Dialog in ASP.NET
I am using hyperlink control. On that i have given link of couple of document and i want that when link is click that document get open.But right now that document is also downloadable. I dont want that some one can download my document. So can any one help me regarding this issue . i m uploading .doc,.pdf,.htm etc files.
# re: Downloading a File with a Save As Dialog in ASP.NET
I would like to raise the open save dialog box when a link is clicked but I don't know how the "transmitFile" code is being used.
Here is what I did
I made a aspx page that looks like this
<html>
<body>
Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition","attachment; filename=Petes.jpg");
Response.TransmitFile( Server.MapPath("~/Petes.jpg") );
Response.End();
<body>
<html>
Then on my website I linked to that aspx page
I doesn't work of course
If some one has time (and pity on a newbee) could they type out an example where "petes.jpg" is in what i guess is the root directory?
Thanks
# re: Downloading a File with a Save As Dialog in ASP.NET
How Can I get original file content with out appending HTML content.
Can any one please help me about this.
Thanks,
Jayanth.
Code:
----------------
Case "Show_File"
Dim SetupLink, strpath, strFileType As String
SetupLink = "Attachments/" + Helper.FixSQL(e.CommandArgument).Replace(";", "€")
SetupLink = Server.MapPath(SetupLink)
If File.Exists(SetupLink) = True Then
'Response.ContentType = "*/*"
Response.Clear()
Response.ClearContent()
strFileType = LCase(Right(SetupLink, 4))
Select Case strFileType
Case ".txt"
Response.ContentType = "text/html"
Case Else
Response.ContentType = "application/octet-stream"
End Select
Response.AppendHeader("Content-Disposition", "attachment; filename=" & Helper.FixSQL(e.CommandArgument))
Response.WriteFile(SetupLink)
End If
--------------------
Orginal file content
Bcc
'abc@microsoft.com'; 'xyz@logicacmg.com'; 'tre@gmail.com'
Appending the code from here to file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>UpdateStageDetails</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
# re: Downloading a File with a Save As Dialog in ASP.NET
<strong>application/ms-excel</strong>
I am wondering I there are other people facing the same problem. I would be great some fresh ideas to get my out of the stack.
Thanks a lot...
<strong>: )</strong>
# re: Downloading a File with a Save As Dialog in ASP.NET
I have the same problem as Jeff said before. I tried the solution proposed by Lic on August 4th, add Response.ClearHeaders() before the Response.End(), but it did not work.
My Error is the same:
"Internet Explorer cannot download "WebForm1.aspx" from the_server."
"The requested site is unavailable or cannot be found. Try again later"
When I add the Response.ClearHeaders(), I receive funny characters in my page like " #,##0\ "$"_);\(#,##0\ "$"\)% #,##0\ "$"_);[Red]\(#,##0\ "$"\)&!#,##0.00\ "$"_);\(#,##0.00\ "$"\)+&#,##0.00\ "$"_);[Red]\(#,##0.00\ " and the save as dialog does not pop up.
Here's my code:
With Response .Clear() .ContentType = "application/octet-stream" .AddHeader("Content-Disposition", "attachment; filename=" + objTargetFile.Name) .AppendHeader("Content-Length", objTargetFile.Length.ToString) .WriteFile(objTargetFile.FullName) End With testBox.Text = "Damn!!"
Also, that's funny because the error only happens on the page_load. On a click event, it works fine, but for the needed purpose, we needed it in the Page_Load.
Anyone has a solution. I'm starting getting crazy with this !
Thanks,
J-S.
PS: I also noticed that even if it looks like to excute the testBox.Text = "Damn!!", it never did because my textbox is always empty, even in a click event.
Anybody knows why ?
# re: Downloading a File with a Save As Dialog in ASP.NET
I have been facing one problem , regarding encoding of file name to be displayed on the Save / Open dialog , while downloading file.
Here is my Download code, ( in ASP.NET 2.0 VS2005 )
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".pdf");
Response.BinaryWrite(fileData);
Response.End();
Where fileData is binary Array and fileName is name of file. Now for "English" file name , there is no problem of encoding. File Name is displayed properly on File Save / Open dialog , while downloading. But , when file Name is in "Japanese" , some encoding problem arises. File Name is shown in wrong japanese / garbage characters.
I receive this fileName from database, which is in UTF-8 encoding. Even this Japanese fileName is displayed properly on screen, in a listing which shows fileName and their size. For Screen , encoding is set to UTF-8.
To tackel this problem, I tried by setting Response.Charset = "SHIFT-JIS", but still then problem persists.
Pls can u help me? I Don't know how to set encoding in Response.AddHeader( ) while showing fileName.
# re: Downloading a File with a Save As Dialog in ASP.NET
I wrote an ASP .NET application to upload files on our server.
Once the file(s) are uploaded and email is sent out containing a link to the file location.
The email's body is a variable of string type and the link used inside the string is a regular html anchor tag as follow:
<a href="http://myserverpath//myfile.ext">Open file</a>
It works perfect.
We now want to make a change so when the link inside the email's body is clicked then, instead of opening the file, a "Save as.." dialog window will be displayed and the user can chose if he/she wants to open/save the file.
Any idea of how can I do this?
Thanks,
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
Pls help me out i am Downloading a File with a Save As Dialog in ASP.NET the problem is that i require full path instead of Filename when user click on the save box full path should be display in the save text box . when i assign FullName or Full path it replaces My c:\ to spaces .. can anyone help me out ..
Response.Buffer = true;
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;inline; filename=" + "c:\asdf\test.pdf");
Response.AddHeader("Content-Length", targetFile.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(targetFile.FullName);
Response.Flush();
Response.Buffer = false;
Response.End();
c:\ it replace to it as space
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
But i want to refresh the page after a file is downloaded , what should i do?
# re: Downloading a File with a Save As Dialog in ASP.NET
I need to download a pdf file using the Open/save dialog box. From what I read, this would require me to use the Response.TransmitFile which assumes that there's already an existing file. How do I save this file to the server and delete it once I used the transmitfile? I've tried using this code:
Response.ContentType = "pdf"
Response.AppendHeader("Content-Disposition", "attachment; filename=" & filename)
Response.TransmitFile(filepath)
Response.End()
File.Delete(filepath)
Since the response has ended it wouldn't step to the "File.Delete(filepath)" code although it displays a dialog box. I've also tried placing the "File.Delete(filepath)" before the response.end but the dialog wouldn't show up this time.
What I need is for the the dialog box to prompt so I can save the file to my local drive and delete the copy saved to the server.
Thanks in advance!
# re: Downloading a File with a Save As Dialog in ASP.NET
How can i do this?
# re: Downloading a File with a Save As Dialog in windows forms using C#.net
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
I'm facing a very strange problem. We have a zip file to be downloaded from the server. The code works correctly in most of the machines. But, on our staging server, when the file is downloaded and saved to the local disk, somehow it gets corrupted. Any idea why this happens.
Please help.. since its urgent!
Thanks in advance
# re: Downloading a File with a Save As Dialog in ASP.NET
Is it possible that the save-as dialog box automatically bids on an e-bay item when the user clicks save? (But only if they click with their left finger)
just kidding :D
Thanks for your blog.
# re: Downloading a File with a Save As Dialog in ASP.NET
After downloading file my browser seems to be stop,the upadte buttona nd download links r not woring.I am using this code
Response.AddHeader("Content-Disposition", "attachment; filename=" + name);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(objEmployeeLeave.FileAttatch);
Response.Flush();
Any can help me plz..
# Showing Microsoft Documents in Popup Window
Thanks so much for figuring out how to show MS docs in popup--I was getting the blank bleep window as well. Why RegisterStartupScript doesn't work, but putting the js in the button itself does, is another Microsoft mystery. I found that changing one of the security settings in IE7 for the internet zone (Downloads--prompt user to download) worked, but asking 150 non-technical users to change their IE settings would have been problematic to say the least.
Thanks again
# re: Downloading a File with a Save As Dialog in ASP.NET
i'm using transmitfile() to open the file.The file is placed at remote server.If i try to download with localhost its working fine but if i tried same with my machine ip it opens a blank file. Please help
# re: Downloading a File with a Save As Dialog in ASP.NET
This is one of the greatest articles I found in this topic.
I am having a scenario where users saves a form and gets all those values in a PPT file.
This PPT file is getting flushed to the same window. I wanted it to flush it into a new window.
I even did that using form.target = "_blank";
PPT is getting downloaded, but after saving (or open or Cancel) the PPT, new window still remains opened. How can I close this new window?
I am using IE 6.0 as my browser.
Thanks for your time..
-Praveen
# re: Downloading a File with a Save As Dialog in ASP.NET
Jeez, I can't believe all the people on here who are asking for free help... do your own work, guys! How else are you going to learn?
DrGreenSticky
# re: Downloading a File with a Save As Dialog in ASP.NET
I was having the same problem and found that if I used a target of _self, the popup in IE did not show up (which was what I wanted). I also found that I needed to continue to use a target of _blank for FF to work.
Scott
# Mobile devices
I've used code like the one in the article several times over the years and worked great, however I've recently stumbled on a more particular problem: mobile device browsers. They seem to completely ignore the "content-disposition" header and it'll save the file with the name in the request path.
Does anyone know a work-around for this ?
Thanks,
Alex
# re: Downloading a File with a Save As Dialog in ASP.NET
# Downloading a xml File with a Save As Dialog in ASP.NET
I need one help regarding download file. I am using showModalDialog insted of window.open. when i am trying to download xml file using ds.writexml(tpath) it is not showing open/save dialog box. i read one article and i used iframes(opening new window, new window contains iframe), then i am getting dialog box. I am able to save tat generated xml file, but i am not able to open that xml file in that perticular window. as per my requirement i should not use _blank in base. I need any one solution out of these 2, either open button disable or open tat perticular xml file in that window. it is URGENT. plzzzzz helppppp meeeee.
# re: Mobile devices
Hope it helps someone :)
# re: Downloading a File with a Save As Dialog in ASP.NET
I have Gone Through this discussion,I too have a Question for you..
I need to get the path of the folder,even the person is selecting file or not using fileupload control..
can any one suugest me to proceed futher on this.
Thanks in advance
Ashok
# re: Downloading a File with a Save As Dialog in ASP.NET
I went through your interesting article. It tells a lot but I am facing some other strange problem with downloading file.
I used both approaches (TransferFile(...) and also Response.OutputStream.Write(...)). The strange thing is that it works but only for second time when client ask for a file. More precisly:
- Headers for both response are equal, but the first attempt is cancelled. Not sure by who, by server or client?
- On client side it doesn't open any Save as dialog for sure. Fiddler just tells me that first attempt was cancelled by Server or Client.
- I used construct with extra Download aspx page that take care of generating or picking up the file from File system and should open the Save as dialog.
Does anyone had theis issue before? Any suggestion helps. Thanks in advance.
Xabatcha (xabatcha at gmail ;-) )
# re: Downloading a File with a Save As Dialog in ASP.NET
Internet Explorer cannot download from ...ntMain$_ctl4$lnkSubject',").
No such interface supported
what is going on there??
here is the piece of coding doing the work:
Response.ContentType = "Application/Zip"; Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); Response.OutputStream.Write(imageRow.IM_IMAGE, 0, (int)imageRow.IM_IMAGE.Length); Response.End();
# re: Downloading a File with a Save As Dialog in ASP.NET
I need to download multiple files, may I know how am I able to do that other than zipping the files up ? (because I can't control my users to zip the files before uploading)
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
# How to open Save As dialog Box without getting the first window containing Open,Save,Cancel,More info buttons.
First of all thanks for ur explanation. It really helped me in my Project. But my problem goes one step further. Instead of showing the client the first window containing Open,Save,Cancel,More info buttons and then after clicking on the Save button; the Save as dialog box appears right.
I need to show directly that Save as dialog box as soon as Button is hit.
I have tried it a bit. Could u help me in. It will really get me going further in my project work.
Reply ASAP...
Bye n Thankx
Prash
# re: Downloading a File with a Save As Dialog in ASP.NET
I have gone to your code.
It would be help ful if i get a complete code of it.
Thanks
Sneha
# re: Downloading a File with a Save As Dialog in ASP.NET
Response.Clear();
Response.ContentType = "application/zip";
Response.AppendHeader("Content-Disposition", ("attachment; filename=xyz.zip"));
Response.TransmitFile(Server.MapPath("/download/xyz.zip"));
Response.End();
and that's it. This is the required i suppose. Find ur file by Server.Mappath() and attach it to this. Mr Rick had stated the same procedure; nothing more to add. Its simple... Thanks to Rick.
Thanks
Prashant
# re: Downloading a File with a Save As Dialog in ASP.NET
I enjoyed seeing you at DevConnections in Vegas. Glad you made it home okay!
This article was really helpful and I'm running into a situation where the downloaded file is blocked by IE6 / IE7 on XP/SP2, where the Information Bar says "The file download was blocked..." etc. That's all fine, but when the user clicks the Information Bar and then "Download File..." the file does not download, but the page just refreshes.
If the user tries to download again, the download works fine.
I understand that if the user sets the "Automatic prompt" to Enable under File Downloads, they can avoid the Information bar, but my real question is, why doesn't the initial download work after choosing "Download File..." from the Information Bar.
I'm using a dynamically created IFrame that points to my ASPX page to initiate the Response.Transmit file. Any suggestion on how to get IE to actually transmit the file the first time the user hits "Download File"?
Denver Mike
# Downloading a File from database using C#
1st this code is running successfully uploading to Database
protected void btnUploadPic_Click(object sender, EventArgs e)
{
int len = FileUpload1.PostedFile.ContentLength;
byte[] pic = new byte[len];
FileUpload1.PostedFile.InputStream.Read(pic, 0, len);
SqlConnection cnn = new SqlConnection(sqlcnstr);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand(" insert into IssueAttachment (IssueID,attachmentDate,AttachmentType,Attachment) values (@IssueID,@attachmentDate,@AttachmentType,@Attachment)", cnn);
cmd.Parameters.AddWithValue("@Attachment", pic);
//cmd.Parameters.AddWithValue("@IssueAttachmentID", txtIssueAttachmentID.Text);
cmd.Parameters.AddWithValue("@attachmentDate", DateTime.Now);
cmd.Parameters.AddWithValue("@AttachmentType", txtAttachmentType.Text);
cmd.Parameters.AddWithValue("@IssueID", drpIssueID.Text);
cmd.ExecuteNonQuery();
lblMsg.Text = "the Picture has Uploaded Seccessfully";
}
catch (Exception err)
{
lblErmsg.Text = "Error Reading the Picture" + err.Message;
}
finally
{
cnn.Close();
}
lblMsg.Visible = true;
}
//-------------------------------------------
this one for Downloading is disaster It cannot Download Anyone who is willing to Please guys help cos I need some life savoir
protected void btnDownLoad_Click(object sender, EventArgs e)
{
MemoryStream mrt = new MemoryStream();
string[] files=null;
FileInfo file;
string Filename;
//Define sql select statement
string sqlse = "select * from IssueAttachment where IssueID ='" + IssueAttachmentID.ToString();
//create Connection
SqlConnection cnn = new SqlConnection("Data Source=EJMSERVER;Initial Catalog=EJMIssueTracking;Integrated Security=True");
SqlCommand cmd = new SqlCommand(sqlse, cnn);
try
{
cnn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
Response.Clear();
//Set the The Content to the ContentType of our File
Response.ContentType = (string)dr["AttachmentType"].ToString();
//Write Data out of databaseinto Output stream
Response.OutputStream.Write((byte[])dr["attachment"], 0, (int)dr[""]);
Response.AddHeader("Content-Disposition", "Attachment; filename=" + GridView1.DataSource);
// Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "Application/octect-stream";
//Response.BinaryWrite(
//Response.WriteFile(Filename);
Response.StatusCode = 404;
byte[] attachmentSize = new byte[102400];
Response.BinaryWrite(attachmentSize);
}
catch (Exception err)
{
lblmsg.Text = err.Message;
cnn.Close();
}
finally
{
Response.End();
}
}
Guys I spend sleepless night and days try to solve this mess but only nothing is right
# Downloading a File with a Save As Dialog in Mobile
Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition","attachment; filename=SailBig.jpg");Response.TransmitFile( Server.MapPath("~/images/sailbig.jpg") );
but this code is not able to open "Save as dialog box " on mobile Browser .Could anyone please tell me How to open "Save as dialog box " in mobile . i am using XHTML ( not WAP ) with ASP.NET & C# .
# re: Downloading a File with a Save As Dialog in ASP.NET
Iam trying this
byte[] a = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(result);
MemoryStream objMemoryStream = new MemoryStream();
objMemoryStream.Write(a, 0, Convert.ToInt32(a.Length));
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "message/rfc822";
Response.AddHeader("content-disposition", "attachment;filename=" + strfilename + ".mht");
Response.OutputStream.Write(objMemoryStream.GetBuffer(), 0, Convert.ToInt32(objMemoryStream.Length));
Response.OutputStream.Flush();
but instead of getting the actual file name iam getting the aspx page. what could b the issue? Please help.
# re: Downloading a File with a Save As Dialog in ASP.NET
Great article. I have a slight twist on this. I need to download an mp3 from a remote url in IE6. (IE7 works by simply adding the following:
Response.AddHeader("Content-Disposition", "attachment;filename=" + link);
Do you have a code example of how to do this in IE6? I've tried the following:
protected void Page_Load(object sender, EventArgs e) { //I get the link from the querystring here - that code has been left out if (link != null) { byte[] _data; _data = this.LoadFromURL(link); Response.BinaryWrite(_data); Response.Flush(); Response.End(); } } protected byte[] LoadFromURL(string url) { // create a request for the URL WebRequest wr = WebRequest.Create(url); byte[] result; byte[] buffer = new byte[4096]; // get the response and buffer using (WebResponse response = wr.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (MemoryStream memoryStream = new MemoryStream()) { int count = 0; do { count = responseStream.Read(buffer, 0, buffer.Length); memoryStream.Write(buffer, 0, count); } while (count != 0); result = memoryStream.ToArray(); } } } return result; }
I'm calling this page from the original download link so that I can track someone has clicked the link, and I'm passing the remote link to download as the querystring variable link. What I get is an attempt to download the page name (DownloadTrackIt.aspx).
Any suggestions on how I can do this or what might be wrong with this code? Your help would be greatly appreciated.
# re: Downloading a File with a Save As Dialog in ASP.NET
protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["link"] != null) link = Request.QueryString["link"]; int lastIndex = link.LastIndexOf("/"); fileName = link.Substring(lastIndex + 1, (link.Length - lastIndex - 1)); Response.Clear(); Response.ContentType = "audio/mpeg3"; Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName); if (link != null) { byte[] _data; _data = this.LoadFromURL(link); Response.BinaryWrite(_data); Response.Flush(); } } protected byte[] LoadFromURL(string url) { WebRequest wr = WebRequest.Create(url); byte[] result; byte[] buffer = new byte[4096]; using (WebResponse response = wr.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (MemoryStream ms = new MemoryStream()) { int count=0; do { count = responseStream.Read(buffer, 0, buffer.Length); ms.Write(buffer, 0, count); } while (count != 0); result = ms.ToArray(); } } } return result; }
If you know of a better way, please let us know.
# HOW ZIP? Downloading a File with a Save As Dialog in ASP.NET
Very interesting! I tried to use your suggest.
Now a question: I saved a lot of excel files on server. I wish that the end user downloads the files on his PC. I don't like single operation for single file.
How can I zip all files on server?
And, after having zipped them, can end user download and save the zipped file on his computer?
Any ideas? I thank all of you!
Tappat
# Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
I seem to have the same/similar issue as "Simit" has with the filename in the dialog box.
Your reply: "The way the file is displayed (in browser or Save As) is determined by the server, not the client"...
Can you please try to enlighten me on what I can modify on in the handler to get the name in the "open / save / cancel" dialog to be correct?
(I tried changing Response.EncodingType without any luck.)
My example: 1æ.jpg is the actual filename, in the website it is encoded as: 1%C3%A6.jpg and in debug mode (I fetch the file though a handler) the filename is always with the (Norwegian) letter "æ", then in the save dialog it is: 1Ã|.jpg, not very nice.
Cheers!
/Robert
# re: Downloading a File with a Save As Dialog in ASP.NET
On click of a button, I am able to download all the files from database and also saving to hard disk of the server with out any Save dialog box. But i want to save the files at client machine rather than saving at server.
Could you please help me out to do this.Its very urgent...
Thanks in advance...
# re: Downloading a File with a Save As Dialog in ASP.NET
I use an iframe to view files (.doc and pdf). When I run the aplication on my localhost it works fine. On the live aplication server it also works fine in Firefox, but in Internet Explorer 6, I only get the option to download pdf's and when I click to view a .doc I get a message saying: can't download file from server.
Could anybody help me with this issue?
Thanks!
# re: Downloading a File with a Save As Dialog in ASP.NET
I've seen others ask about this but so far no one has answered. Just wondering if you or anyone has figured this one out.
I want to be able to open file types recognized as web files (.html, .htm, .xml, etc.) from the File Save dialog in a new browser window. I know I can set the hyperlink URL to "_blank". However, this causes the window to open before the dialog. If the user clicks "Cancel" in the dialog, it leaves the blank browser window.
Any ideas on how to either force the empty window to close, or to not open it until and if the user clicks "Open"?
Thanks,
Carl
# re: Downloading a File with a Save As Dialog in ASP.NET
But if you're trying to force a Save As... operation in the first place why open a new window? In the local window the window stays as it is so you don't lose anything.
# re: Downloading a File with a Save As Dialog in ASP.NET
Read your log and it works great.
When you have a file.
But got a question about this, wich is:
Is it allso possible to simulate the right click "Save Target As"
when the target is an other APS page that has to be generated
I have a ASP. page that gets some HTLM-code from the database
and then displays it to screen, there I want the option to
Print it (this works) but now want it to be saved (to client disk).
If i right click the link and say save as (.DOC or .HTML ) it works
was wondering if its possible to use your solution, but till now no success
Thanks in advanced
# re: Downloading a File with a Save As Dialog in ASP.NET
string statement = @"<script language=""javascript"" type=""text/javascript"">" + string.Format(@"window.open('{0}', null);", ResolveClientUrl(filepath)) + @"</script>"; ClientScript.RegisterStartupScript(this.GetType(), "RunStatement", statement);
This will ensure that all the code & postback is done. With response.end() no code is excecuted after it.
Hope it helps
# re: Downloading a File with a Save As Dialog in ASP.NET
I would like to know if it's possible to download TIFF images.
I've tried multiple code but the file image is always recognized as JPG image and not TIFF.
Have you any ideas ?
Thanks,
# re: Downloading a File with a Save As Dialog in ASP.NET
it will work for a single file.
but i wnat for multiple file
when i check multiple check boxes in a gridview then it should download files to my disk
# problem in viewing MHTML report when it is Exported
Name: wbk3E.tmp
Type: HTML DOcument
From :mhtml:http://localhost/riq/web/UI/RunReports.aspx
wbk3E.tmp file is not displaying any report data, I am not getting what happens when I click on Open button..The same code is working on first request and its alternative requests fails to show the report...I don't have any problem with CSV and XML exports.
Please suggest me what is the problem in opening the report on Even open clicks. The below lines of code that renders the report.
try
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
switch (_format)
{
case "MHTML":
Response.ContentType = "text/mhtml";
Response.AddHeader("Content-disposition", "attachment;filename=output.mhtml");
break;
}
Response.OutputStream.Write(m_bytes, 0, m_bytes.Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
Response.Flush();
Response.Close();
Response.End();
}
Any help on this is appriciated.
-- Raghu
# re: Downloading a File with a Save As Dialog in ASP.NET
In my project I used a file download dialog box using the same code as given in the above article. My problem is: How we confirm programmatically that file download is completed or not, such that I can update my database. I need a file download confirmation when user click on 'Save' button & completed the file download process.
# re: Downloading a File with a Save As Dialog in ASP.NET
iam using the following code to open or save a file.
it is doing save perfectly.
the problem is..
when iam trying to click on "open" button in filedownload window
first time it is not opening the file..instead of that it is again showing the file download window..
second time if i click on open it is opening the file..
why it is showing filedownload multiple times..
in IE7 it is working fine..in IE6 only it is showing above behaviour..
string serverpath = Server.MapPath("");
string fname = "btnBrowse.gif";
serverpath = serverpath + "\\" + fname;
System.IO.FileInfo file = new System.IO.FileInfo(serverpath);
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fname);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "binary/octet-stream";
Response.WriteFile(serverpath);
Response.End();
pls help me..
thanks
with regards
sekhar
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
I wrote a code to download an excel using Response.Transmitfile();
Below Code Working fine when I am working in local system.
eg: http://localhost/website working fine.
Same code with IpAdress or from server not working
Eg: http://192.168.1.44/website Not working
code :
FilePath = "Excel/Activity.xls";
DestFileName = "Activity.xls";
Response.Clear();
Response.ContentType = "application/ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + DestFileName.Trim());
Response.Charset = "";
Response.TransmitFile(FilePath);
Response.End();
Working fine in Localsystem,
From server not working
# Want to view MHTML file in browser, unbale to view images of file in browser
i am able to view mhtml file in browser, but images are not displaying in the browser window.
could you help me how to view complete mhtml file with images in browser.
********Here is my code***********
string filepath = null;
filepath = @"C:\sunder\R&D\WordFileConverter\WordToHtml\withiamge.mht";
FileStream objFile = new FileStream(filepath, FileMode.Open);
MemoryStream storeStream = new MemoryStream();
storeStream.SetLength(objFile.Length);
objFile.Read(storeStream.GetBuffer(), 0, (int)objFile.Length);
byte[] prescan = storeStream.ToArray();
StreamReader reader = new StreamReader(storeStream);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "message/rfc822";
Response.AddHeader("Content-Type", "message/rfc822");
Response.AddHeader("Content-Disposition", "inline;filename=file.mhtml");
//Response.BinaryWrite(prescan);
Response.OutputStream.Write(prescan, 0, prescan.Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
Response.Flush();
Response.Close();
Response.End();
if any have solution then please post here.
Thanks,
Sunder Chhokar
# Want to view MHTML file in browser, unbale to view images of file in browser
i am able to view mhtml file in browser, but images are not displaying in the browser window.
could you help me how to view complete mhtml file with images in browser.
********Here is my code***********
string filepath = null;
filepath = @"C:\sunder\R&D\WordFileConverter\WordToHtml\withiamge.mht";
FileStream objFile = new FileStream(filepath, FileMode.Open);
MemoryStream storeStream = new MemoryStream();
storeStream.SetLength(objFile.Length);
objFile.Read(storeStream.GetBuffer(), 0, (int)objFile.Length);
byte[] prescan = storeStream.ToArray();
StreamReader reader = new StreamReader(storeStream);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "message/rfc822";
Response.AddHeader("Content-Type", "message/rfc822");
Response.AddHeader("Content-Disposition", "inline;filename=file.mhtml");
//Response.BinaryWrite(prescan);
Response.OutputStream.Write(prescan, 0, prescan.Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
Response.Flush();
Response.Close();
Response.End();
if any have solution then please post here.
Thanks,
Sunder Chhokar
# re: Downloading a File with a Save As Dialog in ASP.NET
My SaveAs dialog box works OK, but I have a very specific problem that may be related to browser settings, but I can't work out how to solve it!
I have a page from which the user can generate a Word document, which is posted back to the user as a MIME attachment. That's not the problem as such, as it works with Firefox on the XP machine that I'm developing on. However, on another XP machine, after the attachment is saved, all the buttons on the page that use javascript:__doPostBack no longer work, as though the event isn't generated. All the same buttons work fine before the attachment is downloaded, its only afterwards that the problem emerges. Buttons that load different pages work fine too, its only postbacks that become a problem.
Its a bit odd, as I can't recreate the problem on my XP machine, and I can't figure out any significant difference in the configuration of Firefox either. I assume it must be some client-side configuration issue, but do you have an idea of what I'm missing? I thought it might be some security setting that I don't know about, maybe not in the browser at all? Please help if you can!!
Regards Paul
# re: Downloading a File with a Save As Dialog in ASP.NET
Great article rick..
I wish to know whether using the method described in the article, i shall not receive the following error: process is being used by another process.
this error happens when while someone downloads a picture x, another person also is donwloading the picture x at the same moment.
Do you have an equivalent of response.Transmitfile for asp.net 1.1?
Thnks
# re: Downloading a File with a Save As Dialog in ASP.NET
I was wondering if somebody could tell me what is wrong with the code I am using, I am having some problems, for example only one client could download the file, two people can not download it at the same time, even though same client could download it more than one time concurrently. I have asked some friends to test it and it downloads 0 byte to their computer. another problem is that it is hard to navigate to the website while the file is being downloaded.
here is the code:
int i = _DownloadID;
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/download";
Response.AddHeader("Content-Disposition:", "attachment; filename=" + i + ".wma");
Response.AppendHeader("Content-Length", "contentlength");
Response.AppendHeader("Connection", "close");
Response.TransmitFile("~/downloads/"+i+".wma");
Response.Flush();
Response.End();
---
I treid to download remote file using various methods like this one:
string url = "http://xxxxxxxxx/downloads/" + i + ".wma";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "application/download";
Response.AddHeader("Content-Disposition:", "attachment; filename=" + i + ".wma");
Stream responseStream = response.GetResponseStream();
int bytesRead=(int)response.ContentLength;
byte[] buffer = new byte[response.ContentLength];
while ((bytesRead = responseStream.Read(buffer, 0, (int)response.ContentLength)) > 0)
{
Response.OutputStream.Write(buffer, 0, bytesRead);
}
Response.Flush();
Response.End();
and the problem with that is it downloads it to memeory and the website would hang until the file is finished after that it prompt the customer to save the file, but for a normal customer they would think there is something wrong with the website.
that what made me switch to Transmit file method and store the file locally instead of remote. I would appreciate any help with both.
# re: Downloading a File with a Save As Dialog in ASP.NET
I've a problem, when I push a file from server-side, IE-7 blocks it and displays a bar that "To help protect your security, Internet Explorer blocked this site from downloading files to your computer".
So is there any way to unblock it using C#.NET?
ALI
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
Thanks
Jason
# re: Downloading a File with a Save As Dialog in ASP.NET
It is very nice article. But I have different problem, when user clicks button we normally stream the data and open the document but I want that file to be sent to printer[clientside] directly without showingthe document to client. Any solution?
Thanks in advance....
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
Setting content length is required only when output is not buffered and sent in chunks (ie. you'r doing your own Response.Flush() and completion dynamically). In those cases it can help browsers determine the end of the content.
# re: Downloading a File with a Save As Dialog in ASP.NET
I am trying to download a file from ftp server. I have a grid which displays the list and when the user selects one, I open a pop-up where the download occurs.It is working nicely but when unless I try to show an image while the download process is going on, I get the above mentioned error.
/*****************Code for image display**************************/
const string MAIN_IMAGE = "/_layouts/images/novartis/waiting.gif";
const int PROGRESS_BAR_SIZE = 10; //number of steps in your progress bar
const string PROGRESS_BAR_STEP = "/_layouts/images/novartis/pik.gif"; //image for idle steps
const string PROGRESS_BAR_ACTIVE_STEP = "/_layouts/images/novartis/pik.gif"; //image for active step
Response.Write("<div id=\"mydiv\" align=\"center\">");
Response.Write("<img src=\"" + MAIN_IMAGE + "\">");
Response.Write("<div id=\"mydiv2\" align=\"center\">");
for (int i = 1; i <= PROGRESS_BAR_SIZE; i++)
{
Response.Write("<img id='pro" + i.ToString() + "' src='" + PROGRESS_BAR_STEP + "'> ");
}
Response.Write("</div>");
Response.Write("</div>");
Response.Write("<script language=javascript>");
Response.Write("var counter=1;var countermax = " + PROGRESS_BAR_SIZE + ";function ShowWait()");
Response.Write("{ document.getElementById('pro' + counter).setAttribute(\"src\",\"" + PROGRESS_BAR_ACTIVE_STEP + "\"); if (counter == 1) document.getElementById('pro' + countermax).setAttribute(\"src\",\"" + PROGRESS_BAR_STEP + "\");else {var x=counter - 1; document.getElementById('pro' + x).setAttribute(\"src\",\"" + PROGRESS_BAR_STEP + "\");} counter++;if (counter > countermax) counter=1;}");
Response.Write("function Start_Wait(){mydiv.style.visibility = \"visible\";window.setInterval(\"ShowWait()\",1000);}");
Response.Write("function Stop_Wait(){ mydiv.style.visibility = \"hidden\";window.clearInterval();}");
Response.Write("Start_Wait();</script>");
Response.Flush();
/**************Code for download**********************/
if (Request.QueryString["DownloadUrl"] != null)
{
FtpWebRequest reqFTP;
//HtmlControl frame1 = (HtmlControl)this.FindControl("frame1");
//frame1.Attributes["src"] = "Iframe1WebForm.aspx";
try
{
string fileName = Request.QueryString["DownloadUrl"].ToString();
string filename = Path.GetFileName(fileName);
WriteLog(filename);
Response.Buffer = true;
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.ContentType = "application/octet-stream";
////Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.Flush();
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + filename));
WriteLog(reqFTP.RequestUri.ToString());
reqFTP.Proxy = null;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword, ftpDomain);
//WebResponse aa = reqFTP.GetResponse();
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
MemoryStream MemStream = new MemoryStream();
int bufferSize = 102400;//2048;
byte[] respBuffer = new byte[bufferSize];
try
{
int bytesRead = ftpStream.Read(respBuffer, 0, respBuffer.Length);
WriteLog("byteRead" + " " + bytesRead.ToString());
while (bytesRead > 0)
{
MemStream.Write(respBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(respBuffer, 0, respBuffer.Length);
WriteLog("inside while" + bytesRead.ToString());
}
byte[] finalByte = MemStream.GetBuffer();
Response.BinaryWrite(finalByte);
}
finally
{
ftpStream.Close();
response.Close();
}
}
catch (Exception ex)
{
throw ex;
}
# re: Downloading a File with a Save As Dialog in ASP.NET
I am doing the download proces in a pop-up window and want to close the pop-up after the download completes and the Save dialog box appears. But I am unable to close the window, even through javascript. it seems that after Response.BinaryWrite no other script works. please help me. !!!
# re: Downloading a File with a Save As Dialog in ASP.NET
The user will not actually be redirected to pagename.aspx, because in the page load event for this page we call response.end at the end of Rick's "save as" routine - however, the dialog
will appear and enable the user to save the file as expected.
This obviously is not ideal as you will need a seperate aspx page for every file you want to offer for download and ensure that the correct filename is being referenced in the page load event of each page. However, I personally think this is a small overhead as it does not take long to create a simple "out of the box" aspx page, with no master applied etc.
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
in my project i use a hyperlink in datalist on hyperlink click i want a text file open in own extension . file path comes from database...........
pls if u have any good pls send me
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
I am struggling with some aspects of this code, for instance I have to use Response.End(); but by doing so I stop the execution of the page and I cannot do anything else, and there are some thing I would like to do, for instance show user that he download was successful, prompt him to go to home page, or I don't know redirect him to a page somethig like SuccessfulDownload.aspx
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
I am facing a very strange problem with the download code, I have written a code to download a file from the server. The flow of download is that user clicks on link of the file, a pop up opens with "Open/Save/Cancel" dialog if user selects 'Open', the popup get closed and the file is opened with the application associated with it.
We are able to get this behavior on the machine which has Windows 2003 server and IE 6 / IE 7 or a machine with Windows XP and IE 7.
But when we are trying to download a file from a machine which has Windows XP and IE 6 on it the blank popup remains open and file is also opened in the associated application. our clients are annoyed with this behaviour.
Most of our clients have XP machine and we can't force our every user to migrate to IE7, We have tried our best ways to close that blank popup but all is futile.
please help us to solve this problem as soon as possible.
Thanks
Ravi
# re: Downloading a File with a Save As Dialog in ASP.NET
i want to download a file from ftp directory? pls help? iwant to display download dialog box also.
madhu
# re: Downloading a File with a Save As Dialog in ASP.NET
Premise: I have to bring up GAL (at least have access to the outlook address folders of the client machine ) and not depend on Outlook be installed on the webserver off of where our ASP.Net website runs. Our application is built in the ASP.Net 3.5 and C# environment.
My question, is there any way to do?
One idea, that came to my mind is on a client call back, from the RaiseCallbackEvent method, to use something like Response.ContentType or the likes ot it, that to access the client's local outlook folders (address book or GAL). Please let me know, if you have any ideas at the earliest. Any help is greatly appreciated, as I am on a time crunch. It would be nice if I could access the GAL window as is, since then the effort to build a GAL look alike window can be avoided.
pankaja_shankar@ml.com
Thanks,
Pankaja Shankar
# re: Downloading a File with a Save As Dialog in ASP.NET
Response.AddHeader "content-disposition","attachment; filename=fname.ext"
# re: Downloading a File with a Save As Dialog in ASP.NET
http://www.aspfree.com/c/a/Code-Examples/File-download-using-C/
Response.ContentType="application/ms-word"; Response.AddHeader( "content-disposition","attachment; filename=download.doc"); FileStream sourceFile = new FileStream(@"F:downloadexample.doc", FileMode.Open); long FileSize; FileSize = sourceFile.Length; byte[] getContent = new byte[(int)FileSize]; sourceFile.Read(getContent, 0, (int)sourceFile.Length); sourceFile.Close(); Response.BinaryWrite(getContent);
# re: Downloading a File with a Save As Dialog in ASP.NET
In my application I stream an excel file to the browser in a new pop-up window.
This works fine, the Open/Save dialog appears as expected and it is using the file name that I specify via the Response.AddHeader(....filename=...) method.
The issue I have is when I leave the first pop-up window sitting there, go back to the original/parent page and generate and display a 2nd excel file ..
For the 2nd pop-up window, the Open/Save dialog once again displays correctly, referencing the NEW unique file name as expected. But when I click "Open" .. I get a Microsoft Excel warning dialog appearing that states..
"A document with the name 'DisplayReport.aspx' is already open. You cannot open two documents with the same name, even if the documents are in different folders. To open the second document, either close the document that's currently open, or rename one of the documents."
If I simply click 'Ok' .. the 2nd excel file does in fact display successfully in the new pop-up window, but sometimes this mysterious dialog hides itself behind other windows so the user doesn't notice it - leaving them staring at an empty pop-up browser window wondering what the hell is going on!
So IE/Excel seems to be latching on to the URL of the pop-up window rather than the one specified in Response.AddHeader(), and it is using this URL to establish "its" idea of what the streamed file is called!
If I could use a different URL everytime this wouldn't be an issue .. but I am already using the unique filename as a QueryString in the URL (Eg.. DisplayReport.aspx?5feb5cc9-f218-42aa-84bd-90189b7c0aeb.xls ) and it doesn't affect the outcome.
Any suggestions of how I can convince IE/Excel that each subsequent Pop-up window contains a NEW/UNIQUE file so as to avoid the Excel warning dialog?
Cheers,
Glenn.
# re: Downloading a File with a Save As Dialog in ASP.NET
We have provided the download a xml file through a popup page(aspx) and do the same above you provided. We have one aspx page and update panel and all other pages are user controls. All user controls will be load on the update panel.When we need to download then we popup a aspx page the generate file and write it to Response object and its works fine.
We have to send large amount of data to the popup page so we avoid the querystring option.
We tried the following ways.
1. We wrote the data in to Session object and using ScriptManager.RegisterClientScriptBlock() and popup the page. We get the following exception while calling End() method on Response object:
{Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}
2. We use the hidden field in the main page and get these values on the end of the popup page and then auto submit the page and download works but it asks from user on IE
"To help protect your security, Internet Explorer blocked this site from downloading files to your computer. Click here for options" We have to right click and then allow to download the file.
3. We set PostbackUrl on the button and it works fine, But after download the Postbackurl has been set on each button so when we click any button then download the same file again and again.
We used javascript and popuped a aspx page and download a xml file and works fine. But we needs to send large data to that popup page and then download.
Could you please give us how to download a xml file from a user control page or how to overcome our issues in the downloading?
Thanks,
Vivekanandan
# re: Downloading a File with a Save As Dialog in ASP.NET
<META name="DownloadOptions" content="noopen">
This would make the Open button invisible
# re: Downloading a File with a Save As Dialog in ASP.NET
Me too realy fight with download file. Here is the code that works
System.IO.FileInfo file = new System.IO.FileInfo(strURL);
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + file.FullName);
Response.AppendHeader("Content-Length", file.Length.ToString());
Response.ContentType = args[2]; //content type from database
Response.WriteFile(strURL);
Response.Flush();
Response.End();
One suggetion to all .net gurus is to store ContentType of file in database if you are storing file path in database and then in code you didnt need to worry about the content type. Just block those extension which you done want while you upload files.
Have Fun
Zafar
http://barchitect.blogspot.com
# re: Downloading a File with a Save As Dialog in ASP.NET
Here is the code block (I tried this in a handler and in a page with the same result)
Response.Clear();
Response.ClearHeaders();
Response.ContentType = "application/octet-stream"; //"audio/mpeg3"; //no diffence
Response.AddHeader("Content-Disposition", "attachement; filename=AudioFile.mp3");
Response.BinaryWrite(mp3);
//Response.Flush(); //no difference
Response.End();Each time the link is clicked, wmp opens up. The handler fires 3 times, the first is the only one with a referrer url. How can I get around this and just prompt the user with a download link?
# re: Downloading a File with a Save As Dialog in ASP.NET
If anyone came across this sitution please help me.
Thanks,
Roji
# Question: Downloading an image File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
Response.Clear()
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/force-download\n"
Response.AddHeader("Content-Disposition", "attachment; filename=TestFile.CSV")
Dim sw As System.IO.StringWriter = New System.IO.StringWriter()
sw.WriteLine("line1")
sw.WriteLine("line2")
sw.WriteLine("line3")
sw.WriteLine("line4)
Response.Write(sw)
Response.Flush()
Response.End()
# re: Downloading a File with a Save As Dialog in ASP.NET
I am able to get the open/save dialogue box. But after saving or opening the file from my page. the controls on the page are getting lost their event firing mechanisum. I mean to save there are 2 buttons one to export to external file using open/save dialogue box as u said and other button is to populate data on a grid.
When you click on export to button it is working and after than i want to click on view in grid button where it is not working .it is not triggering any event.
please tell me where could be the problem.
please mail this to me. my id.... "bathula.rajkumar@wipro.com"
# Downloading a Office 2007 Document with a Save As Dialog in ASP.NET
I had to use
Response.Clear()
Response.ClearContent()
Response.BufferOutput = TrueWithout the use of the above code the returned File had some HTML (XML) Text at its end!
Because of this I had to use Response.AddHeader instead of Response.AppendHeader
I posted a little example in at my blog with the topic:
Downloading a Office 2007 Document with a Save As Dialog in ASP.NET
http://www.duelec.de/blog/?p=214
# re: Downloading a File with a Save As Dialog in ASP.NET
The code looks like this
Response.Buffer = true;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Length", _pdfStream.Length.ToString());
Response.AddHeader("Content-Type", "application/pdf");
Response.BinaryWrite(_pdfStream);
Response.End();
where _pdfStream is a byte stream I get from the server.
It is within an APSX page so when there are no documents the aspx page is loaded and the user sees a no-documents-available-error-message.
Well, I have noticed that on some computers it doesn't display correctly in the browser but asks to save the file. When saved with the extension .pdf it can be viewed without problems.
I guess there is a problem with the browser believing it is
Is there a way to set a filename in the header without forcing the browser to open the save dialog? I want the pdf stream to be displayed in the browser directly, and it would be nice to have the possibility to set a filename so when the user wants to save the file the filename is already set.
# re: Downloading a File with a Save As Dialog in ASP.NET
When an attachment opens after clicking on the link from my website developed in ASP.Net after that if i click on anyother links or if i click on Sign Out the same page loads exactly the same way below & all the content type information & response header along with the file name & contents of the attached file is displayed on the screen.Also I get the error as 'the_Form.__EVENTTARGET' is null or not an object.I am not understanding the problem please if any one could help me on this.
Following is the code in VB.Net i am using to download the attachment
Dim lPath As String = Server.MapPath("") ' get file object as FileInfo
lPath = Path.Combine(lPath, lExamFolderPath)
lPath = Path.Combine(lPath, lReportFileName)
Dim lfile As System.IO.FileInfo = New System.IO.FileInfo(lPath)
If (lfile.Exists) Then 'if the file exists on the server
Context.Response.Buffer = False
Context.Response.Clear()
Dim lContentType As String = ""
'Determine the content type
Select Case (lfile.Extension.ToLower())
Case ".dwf"
lContentType = "Application/x-dwf"
Case ".pdf"
lContentType = "Application/pdf"
Case ".doc"
lContentType = "Application/vnd.ms-word"
Case ".ppt"
Case ".pps"
lContentType = "Application/vnd.ms-powerpoint"
Case ".xls"
lContentType = "Application/vnd.ms-excel"
Case Else
'Catch-all content type, let the browser figure it out
lContentType = "Application/octet-stream"
End Select
Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + lfile.Name)
Context.Response.AddHeader("Content-Length", lfile.Length.ToString())
'Set the content type
Context.Response.ContentType = lContentType
Context.Response.Flush()
'Write the file to the browser
Context.Response.WriteFile(lPath)
'Context.Response.End()
# re: Downloading a File with a Save As Dialog in ASP.NET
I am a newbie in web programming.
I am trying to find a way to open save dialog but I need the open to be disabled.
I know that I need to add <META name="DownloadOptions" content="noopen">
But when I write it in code it does not work:
Response.AddHeader("Content-Disposition", "attachment; filename=sample1_save_with_att.htm");
Response.AddHeader(@"Content-DownloadOptions", @"noopen");
Response.ContentType = "application/octet-stream";
Response.Write(sPageContent);
What am I doing wrong?
Thanks in advance.
# re: Downloading a File with a Save As Dialog in ASP.NET
Anyone likes to put a code for that. would be highly appriciated.
thanks a lot
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
there is no need to add below given line in C# if you want to hide Open button from save dialog.
Response.AddHeader(@"Content-DownloadOptions", @"noopen");
if you have already mentioned in page header
i.e <META name="DownloadOptions" content="noopen">
I applied it and it works fine.
more help can be found at http://msdn.microsoft.com/en-us/library/ms533689(VS.85).aspx
Zafar
# re: Downloading a File with a Save As Dialog in ASP.NET
Response.Clear()
Response.ClearContent()
Response.ContentType = "application/octet-stream"
Response.AppendHeader("Content-Disposition", "attachment;filename=""" & MyDrawingFileName & """")
Response.TransmitFile(MyPath)
Response.End()
# re: Downloading a File with a Save As Dialog in ASP.NET
Lots of great stuff here. Everything however seems to apply only to files that exist on your own server. Is it possible to force the file save dialog for a file that exists elsewhere on the web.
An example of when this may be helpful is in a podcast directory. Lots of mp3 files are accessible for download, but these files exist on servers across the web aggregated through rss feeds. With plain hyperlinks more often than not the files will open within the browser. A savvy user can right click and save file as, but a typical user will not know how to do this (in our case even with clearly written instructions).
Is it possible to force the save file dialog for a file that exists not just on your server but elsewhere on the web? Any help or anyone who can point me in the right direction is greatly appreciated.
Thanks,
Ross
# re: Downloading a File with a Save As Dialog in ASP.NET
Please help. Thanks in advance.
Response.Clear();
Response.Charset = "";
Response.ContentType = "text/plain";
if (txtSaveExport.Text.Length > 0) Response.AddHeader("content-disposition", "filename=" + Server.MapPath("~/Testdo.xml") + ".xml");
StreamWriter xmlDoc = new StreamWriter(Server.MapPath("~/Testdo.xml"), false);
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(xmlDoc);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.WriteXml(xmlDoc);
xmlDoc.Close();
Response.End();# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
Is there a way to set a default download directory and not display a Save As dialog?
Thanks,
Lior
# re: Downloading a File with a Save As Dialog in ASP.NET
There's no control to the download dialog itself and it's by design - your Web page has no control over the client's storage.
# re: Downloading a File with a Save As Dialog in ASP.NET
# Configure Meta Tag At RunTime
it hides the open button when the download pop comes out. works preety good.
but in my case i've got some files. in which some of them should hide open button, Save button or Run Button depend on users authetication.
i've tried programmatically using Response.AddHeader("Content-DownloadOptions", "noopen");
this line does not work. so is there any command using which i can control enabling and
disabling of Run, Open, Save Button.
or is there any way that i can change <META> Tag at run time.
if anyone have solution. plz reply me back on ashish.oorja@gmail.com
Thank You.
# re: Downloading a File with a Save As Dialog in ASP.NET
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); Response.ContentType = mimeType; Response.OutputStream.Write(bytes, 0, bytes.Length); Response.End();
that was working well on another page, and used it in a new project to perform the same task - generate an rdlc report as a PDF for the user to Save. It was not working, and none of your or other remedies helped, until I remembered that the command button was inside an UpdatePanel and that I had failed to declare a Trigger for it. Since neither the UI nor any data was updated, you'd think you could get away w/o the trigger, but adding it was an instant cure. Live and learn.
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
The solution was to convert the link to a linkbutton and then add the control to the postbacktriggers during rowbinding. Hope this can help someone else out.
# re: Downloading a File with a Save As Dialog in ASP.NET
First of all, thanks for this post, this is what I wanted.
But I am facing a serious problem here. I want to implement interoperability for my web application. The idea is to Export the application data to an Excel file (On clients machine) and then Import the same Excel file data in my Application.
Using your code, I tried to save my data in an excel file. When I click the save button of the dialog, I can save the excel file on the client machine in the "Microsoft Office Excel worksheet" format.
The code used for the same is :
var excelXml = GetExcelXml(dsInput, filename);
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Length", excelXml.Length.ToString(System.Globalization.CultureInfo.CurrentCulture));
response.AddHeader("Content-Disposition", "attachment");
byte[] excelData = StrToByteArray(excelXml);
response.BinaryWrite(excelData);
response.End();
Now I try to read the data of the same excel file using the connection string
"string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";"
But when I try to open the connection, it throws and excretion saying "Expected Table is not in required format".
Two observations here :
1. When I open the exported excel file (on client machine) and keep it open and then try to run the application for Importing, the import operation is done successfully without any exception.
2. When I open the exported excel file (on client machine) and do a "SaveAs" operation and save it using the same Microsoft Office Excel Worksheet format, and then try to Import this newly saved excel file, again the application runs successfully without an exception.
Now I guess this is to do with the format in which the file is actually been saved on the clients machine.
Is there any way to skip the open/save/cancel dialog box and open the excel sheet directly and then let the user do the SaveAs operation?
Do u suggest some other way to archive my goal ??
Urgent help will be highly appreciated Rick.
Thanks and Regards
Abhijit
# re: Downloading a XLS File with a Save As Dialog in ASP.NET
This is a web application using ASp.Net and C#.
I am creating an excel file in memory using Microsoft.Office.Interop.Excel COM API's.
After creating the contents in memory , I want to send the contents to the client end as a memory stream using Response.Transmit file (MemStream).
Is there a way of not save the file on the server and just dump the in memory XLS file contents to the Memory Stream or Binary Stream...and then write teh contents using a Response Object to send to the client end.
The users of this web application do not have permissions to create the file on the server end...
# re: Downloading a File with a Save As Dialog in ASP.NET
public bool DownloadFile(string url) { string URL = url; System.IO.FileInfo fileInfo = new System.IO.FileInfo(URL); if (fileInfo.Exists) { HttpContext.Current.Response.ContentType = "application/x-download"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(fileInfo.Name)); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.WriteFile(fileInfo.FullName); HttpContext.Current.Response.End(); } return true; }
Thanks to:
http://forums.asp.net/t/1400567.aspx
# re: Downloading a File with a Save As Dialog in ASP.NET
In my case the code worked on dev/staging but not on production. Unfortunately I couldn't figure out what exactly caused the problem.
Staging worked at first and when I messed out with the permissions started getting the garbled files on that server too. This brings me to the conclusion that it has to be a permissions issue.
Hope this helps.
Nik
# re: Downloading a File with a Save As Dialog in ASP.NET
# how to secure download?
If I encrypt the file in process our users get file encrypted and of cpurse they dont want use any appliction to decrypt.
Do you have any idea? Best regards
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
Downloading a File with a save as Dialog is working fine in window.open method.,
But using showModalDialog() its not working.i.e. I wrote the code Response.AddHeaders(), and Response.WriteFile in a page.This page is opened using winodw.open this is working but in showModalDialog popup its not working
# re: Uploading a File with a Open in ASP.NET
Great stuff!... How about the reverse situation?
In my situation I need to access a webpage (happens to be ASP.NET but not in my control) that fires the fileopen dialog using an upload button or clicking in the filename textbox and makes the user pick a local file and then uploads the file to the wesbite. On successful upload it shows a success message.
Using a C# app on the PC, could I bypass the user interaction and feed it the filename/upload the file using the methods you guys have been researching?
I am not a programmer - but working on the design issues of this project.
Thanks/Micky
# re: Downloading a File with a Save As Dialog in ASP.NET
Brent
# re: Downloading a File with a Save As Dialog in ASP.NET
I've one issue with IE SP2.Am not able to download/export file from IE SP2 which is generated by crystal reports. It's not happening at all the client places. Even am not able to simulate in my work environment.
Here the problem behaviour is...
1) Asp.Net 2.0 Website, IIS 6.0 SP2.
2) No Fire wall & Proxy settings.
3) Trying to download/export the file from generated crystal report.
4)Have given all IE setting properly (i.e Allow downloading, trusted sites, do not save encrypted files).
5)Am able to export/download from IE 7 & Mozilla with out any issues.
6)Started facing this after recent OS patch updations at production. (not sure what are all fixes addressed)
7)Have added a test page with crystal report viewer and able to export/download file without issues.
8)It works with localhost but not with hosted instance.
9)Not sure issue with IE SP2/Recent OS Patches/Network/Caching/ etc..
# re: Downloading a File with a Save As Dialog in ASP.NET
thanks guys
below is the code i used
Response.Buffer = true;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/ms-word";
Response.AddHeader("Content-Disposition", "attachment;filename=" + Request.QueryString["fn"]);
Response.OutputStream.Write(b, 0, (int)b.Length);
Response.Flush();
Response.End();
thanks
satish
# re: Downloading a File with a Save As Dialog in ASP.NET
Response.ContentType = "application/ms-word" Response.AppendHeader("Content-Disposition", "attachment; filename=InstituteBadge2Done.doc") Response.TransmitFile(Server.MapPath("InstituteBadge2done.doc")) Response.End()
# re: Downloading a File with a Save As Dialog in ASP.NET
I am using the following code:
Response.Clear(); Response.ContentType = objAttachment.FileType; Response.AddHeader("content-type", objAttachment.FileType); Response.AddHeader("content-disposition", "attachment;filename=" + Path.GetFileName(objAttachment.FileName)); Response.TransmitFile(strFile); Response.End();
This works perfectly...almost... After running this code, any GIF images on the page stop their animations. Even if I put the file download inside an IFRAME...is still kills all GIF animations on the parent page.
My guess is that the ContentType is messing up the rest of the page after the file is served up.
Is there anyway to fix this? Can the content type of the page be reset once the file is written? Would that even work? I tried using "Response.ClearHeaders()"...but that changed nothing.
Basically, we have a CRM IFrame page that lists documents that are pulled from with Microsoft CRM Annotations. When a user clicks on the document, it sends it to the browser for download. But, the page also has other funcationality as well (full of ajax too). The other functionality continues to work (other buttons and forms still submit just fine)...its just these image animations.
# re: Downloading a File with a Save As Dialog in ASP.NET
Gr8 thread.
I have the following code which is being called from a web page;
Dim ls_Filename As String = "c:\\test.pdf" Dim lo_FileStream As System.IO.FileStream = File.Open(ls_Filename, FileMode.Open) Dim lo_Byte As Integer = CInt(lo_FileStream.Length) If (lo_Byte > 0) Then ' Read the file into a byte array Dim lo_fileData(lo_Byte) As Byte lo_FileStream.Read(lo_fileData, 0, lo_Byte) lo_FileStream.Close() Response.AddHeader("Content-disposition", "attachmesnt;filename=" + ls_Filename) 'Make sure to give a filename Response.ContentType = "applicaiton\pdf" Response.BinaryWrite(lo_fileData) Response.Flush() Response.Clear() Response.End() End If
The browser display the dialog box and let's me open/save the file. Just the way i need it.
The only problem is that the main window that this function was called from becomes inactive. (hour clock cursor) I want the user to keep on using the main window after downloading the file.
Any ideas,
Thanks,
KC
# re: Downloading a File with a Save As Dialog in ASP.NET
My code does not shows a SaveAs dialogue box to download the datagrid into Excel file. My code has no errors. It Doesn't do anything.
I am using this code:
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=Sample.xls");
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.DataSource = dmpset;
dg.DataBind();
dg.RenderControl(htw);
//GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
Please anyone knows helps me.
Thanks in advance...
# re: Downloading a File with a Save As Dialog in ASP.NET
I have an ASP, .net application..I need to export grid data to multiple excel files... i understand from the discussions here it could be achieved .. but I could not understand how!!
can anyone post me the code here to export grid data into multiple excel files...
I undertand it is not possible in a straight forward manner..( one request--> one response ) some people here discussed on JavaScript code through which they achieved this..!!!
Thanks in advance,
# re: Downloading a File with a Save As Dialog in ASP.NET
Thank you for the post.
I tried running this on my local server and works fine. As soon as I put this up onto our live server the result is completely different. I click the save button and I get an error with IE saying
"Internet Explorer cannot download "my_page.aspx" from ourliveserver."
"The requested site is unavailable or cannot be found. Try again later"
I have spent some days to figure out and reading posts.. but no luck..
Any help is freatly appreciated!!
My code is simple:
Dim myfile As System.IO.FileInfo = New System.IO.FileInfo(PhysFilePath)
Response.AddHeader("Content-Disposition", "attachment; filename=" & myfile.Name)
Response.AddHeader("Content-Length", myfile.Length.ToString())
Response.ContentType = "application/octet-stream"
Response.WriteFile(myfile.FullName)
Response.Clear()
Response.End()
The files are stored in a folder in the application.
Thank you so much for the help..
Jyothi
# re: Downloading a File with a Save As Dialog in ASP.NET
string filename = Path.GetFileName(url); context.Response.Buffer = true; context.Response.Charset = ""; context.Response.Cache.SetCacheability(HttpCacheability.NoCache); context.Response.ContentType = "application/x-rar-compressed"; context.Response.AddHeader("content-disposition", "attachment;filename=" + filename); context.Response.TransmitFile(context.Server.MapPath(url)); context.Response.Flush();
# re: Downloading a File with a Save As Dialog in ASP.NET
Response.AddHeader("Content-Length", size.ToString());
# re: Downloading a File with a Save As Dialog in ASP.NET
# re: Downloading a File with a Save As Dialog in ASP.NET
Thank you Very much for your Article.I used it in my Application and it's works fine in some where and Not in some where.My problem is
I have Created a pdf file by using pdfSharp and save in a location.but when i want to open that pdf file on the link button click event down load dialogue box is appear and when i clicked the open button.Adobe Reader throws the Strange Error message.the Error Message is
Adobe Reader couldn't open "invoice__2009[1].pdf because it is either not supported file type or because the file has been damaged(for example it was sent as an email attachment and wasn't correctly decoded)
(my filename is only invoice__2009 but [1] is extra comming in the message)
can you help me for this matter?
Thank You
Pawan
# re: Downloading a File with a Save As Dialog in ASP.NET
Thought I'd post it as this really gave me a headache for a while.
Thanks,
Nathan