Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

Downloading a File with a Save As Dialog in ASP.NET


:P
On this page:

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:

SaveAsDialog

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.

Posted in ASP.NET  

The Voices of Reason


 

Nathan
May 21, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

One note: This technique won't work with png image formats. You can't use the .Save() method on nonseekable streams so you're forced to load it to memory first.

Thought I'd post it as this really gave me a headache for a while.

Thanks,
Nathan

Rick Strahl
May 21, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Right, thanks Nathan for pointing that out. I posted about that issue some time ago as well:

http://www.west-wind.com/WebLog/posts/8230.aspx

Rachit
May 22, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Rick, how about using

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)

Josh Stodola
May 22, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Rachit - it is the content-disposition header that prompts the dialog, not the content-type. "application/octet-stream" is very generic anyways, so I feel that Rick is doing this correctly (as always).

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!

Andreas Kraus
May 23, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Thanks Rick! This is exactly what comes in handy for me right now.

Keep up the good work, cheers,
Andreas

stm
May 23, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

I'm using this technique in the past, the only minor problem I've found is the filename.

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...

Nathanael Jones
May 23, 2007

# Supporting resume

MSDN has an article on resume support also http://msdn.microsoft.com/msdnmag/issues/06/09/webdownloads/default.aspx

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

DotNetGuru
May 27, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick,

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...

Kyle
May 31, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Is there any way to have the file open in a new browser window. After you get the open/save-as dialog, and click open instead of save, I would like the file to open in a new browser window, instead of the one I selected the file from. Under our framework, the back button does not work, so it would be preferable to open the file in a new window.

Thanks

Befekadu
June 01, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

I am trying to write a web app that enables a user to download an xml file from a web page. Here is the simplified version of my code:
    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.

Rick Strahl
June 01, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

You need to use Response.End() to keep further output from being generated. Otherwise the rest of the page and markup will be rendered.

Befekadu
June 04, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Yep, the Response.End() really did work.

Thank you very much!

thara
June 05, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

hi,

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?

Rick Strahl
June 05, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Use:
Response.BinaryWrite()


or if you have the output in a stream write to the ResponseStream as shown in the post.

ASP.NET Forums
June 05, 2007

# Specifying the location of a file that’s automatically generated - ASP.NET Forums


Manjeera
June 06, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,
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

Manoj
June 13, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,

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.

Rick Strahl
June 13, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

No - the download is controlled by the browser since you are just returning an HTTP response. There's no way that I know of to manage this because the download process on hte client because of security issues.

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.

D-ko
June 20, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Great article - very useful - but in Firefox, the save dialog opens, and it saves the file but without a file extension! It works great in IE. Any suggestions on how to fix this?


June 22, 2007

# Downloading a File with a Save As Dialog in ASP.NET(下载文件时出现一个保存对话框) - yinix - 博客园


Sandy
June 28, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Rick,

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

Rick Strahl
June 28, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

You can send back anything you want but the browsers only understand a single file return. There's no way to tell the browser that multiple files are returned.

If you need to return multiple files you should zip them and send the compound Zip file back to the client instead.

Sandy
June 28, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Yeah, I guess so.
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.

David Bell
June 29, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick,

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?

ScottGu's Blog
July 04, 2007

# May 22nd Links: ASP.NET, Visual Studio, Silverlight, WPF and .NET - ScottGu's Blog

ASP.NET, Visual Studio, ASP.NET 2.0, .NET

Abhay Khanwalkar
July 04, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,
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.

Rick Strahl
July 04, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Abhay - that's a common scenario for downloads and you can't do this with a straight page because you obviously can return only one response. There are ways to do this with client script though. You can perform the upload in an IFrame as a separate link and have the main page in the meantime display a 'Working' dialog which gets updated on completion.


July 04, 2007

# 本周ASP.NET英文技术文章推荐[05/20 - 06/02] - Dflying Chen @ cnblogs - 博客园


Ved Prakash
July 05, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Oops!! It works!!!

Abhay Khanwalkar
July 05, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

I did the same thing, used Iframe to download the file.Anyway,Thanks a lot

ASP.NET Forums
July 05, 2007

# Opening the files in an modless window. - ASP.NET Forums


Khyati
July 06, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

How to open the downloaded file in a new window instead of same browser window?

Rick Strahl
July 06, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Use a Target tag in your link or form that fires the download.

LarryW
July 06, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Rick,

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,

Rick Strahl
July 06, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

UpdatePanel does not support file uploads due to the multi-part file encoding etc.

If you want do uploads of files 'independently' of the page, stick the file upload component into an IFRAME and process that separately.

sj
July 10, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

hi,

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.

mumbaiusergroup
July 10, 2007

# Downloading a File with a Save As Dialog in ASP.NET


sjelen
July 11, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

For download to work in UpdatePanel you must manually add trigger. Select Triggers property, select Add->PostBack Trigger and set ControlID to your download button. That way page will post back, but download will work. Hope this helps.

DD
July 11, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Is it possible to download the file without popping up the Save As dialog?
I wish to perform a silent download of the file in the background without any under interaction.

Any help would be appreciated.

Thanks.

Rick Strahl
July 11, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

No you cant do that. Huge security risk.

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.

ASP.NET Forums
July 12, 2007

# How can I download a file - ASP.NET Forums


Craig
July 13, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Great Rick!

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()

Craig
July 13, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Update: We were able to solve our issue by setting a couple of session variables and using the registerclientscriptblock. Very sweet!

ClientScript.RegisterClientScriptBlock(....)

Micheal Roger
July 17, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi everyone,
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

Confused
July 24, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Rick,
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();

Rick Strahl
July 24, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

I bet your using IE, right?

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).

Jeff Yates
July 26, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick,

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()

David E
July 30, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hello all
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

Rick Strahl
July 31, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

@David - that can't be done and for good reason. It'd be a huge security risk if files just started saving themselves automatically from the server.

@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.

Lic
August 02, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Jeff - i had same problem and found solution. Add "Response.ClearHeaders()" to your code (before Response.End()). For more info read this site:
http://support.microsoft.com/default.aspx?scid=KB;EN-US;q316431

timematcher
August 02, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi...
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&gt

Kelly
August 04, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

What if the image I want the user to download is an image dynamically generated by an HttpHandler and available only through it's Url? Furthermore, the image is unique to each user's context (i.e. I don't think WebRequest.Create() will work to grab a response).

I don't know how to get a stream representing this handler's output.

Rick Strahl
August 04, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

If a handler creates the image the handler needs to take the TransmitFileAction and add the headers as needed. If you link such an image from your page you can force it to download by maybe passing query string parameters to it that trigger the alternate return result.

Kelly
August 04, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Wow, very nice, Rick! Can I buy you a beer? Definately overlooked solution on my end. I appreciate the reply. Thanks for all your work.

Nehal
August 05, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,

Can we have just the Save option and not the Open button in the pop up?

Rick Strahl
August 06, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

No you can't change the way the dialog looks. The dialog is controlled by the browser.

Sree
August 06, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick

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

A.Abrahams
August 08, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Is there a way of getting the ie7 information bar not to come up when one is streaming the file
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 .

Cristi
August 20, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,

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

Cristi
August 20, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Never mind, I found the issue. ASP.NET was throwing an "Thread was being aborted" error and the writer was appending this information at the end of the downloaded file as I had the download code inside a try / catch. Took it out of the try / catch and everything works fine now.
Thanks Rick for these kind of posts, they are very useful.

Cristi

venkatesh
August 21, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi..

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

Nice
August 27, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

when I am trying to save an image,it is always saving the aspx page..when trying to open the file(from the dialogue box) it is opening..The problem is with the save as option..Can u help me?This is what I am trying to do

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..

Rick Strahl
August 27, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

You don't want the path - you want just the filename. The browser can't make sense out of the path and certainly won't apply it. The filename is provided only for the dialog.

Rob
August 27, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

I am trying to "automatically" save a file. The following opens a PDF in the browser. I’m looking for a way to generate the same file so that it can be saved to the server without user interaction. I don't want the user to be prompted; I just want the PDF to automatically save. Is there a way to programmatically save the file?

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?

Jerry Tovar
August 29, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Rick,

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

Rick Strahl
August 29, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

TransmitFile requires the file you're downloading is in path of the virtual path structure. If it's outside you have to stream the file.

Preeti Mathur
August 29, 2007

# Downloading a File with a Save As Dialog in ASP.NET

Hi..
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?

Jerry Tovar
August 30, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Rick,

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

Adam
September 04, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,
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.

Erik
September 07, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

I'm having a really weird issue using this method. Anyone have any ideas?

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?

Erik
September 07, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Answering my own question. Still not sure of the underlying cause, but I changed the javascript from code behind RegisterStartupScript to putting it directly on the button. And that fixed it.

Apparently some IE security feature.

Simit kulkarni
September 08, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick,
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?

Simit Kulkarni
September 10, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,
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.

Sanjoy Das
September 11, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,

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?

Jack
September 14, 2007

# Downloading a File with a Save As Dialog in ASP.NET

Hi..
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.

Peter
September 16, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

I'm new to all this. I have only used asp once in the 5 months that I've been fumbling around with the web.

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

Jayanth
September 19, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

I have written code for open a file from repeater link. The problem is Source code or HTML content is also appending with that file when we try to open the file. It is happening only for text file.

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">

ale3
September 25, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

I am trying this example with an xls file. The problem is that when I open the file(before or after saving), all the actual file is appended inside a cell of the xls file in raw format. I have tried a lot of examples that I found on the net, but none looks like working with content types like
<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>
.

JS
September 26, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi all,

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 ?

Simit Kulkarni
October 09, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick,
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.

Melina
October 11, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Rick,

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,

Rick Strahl
October 11, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

The way the file is displayed (in browser or Save As) is determined by the server, not the client so if you want both behaviors based on the situation or user choices you have to parameterize the URL. Pass a query string that gives you a hint how to serve the content.

Raj Sharma
October 17, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi All,,
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

David
October 19, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Found this page and it helped! Great stuff. You can be God for the day.

Mahalingam
October 29, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Great things to learn.
But i want to refresh the page after a file is downloaded , what should i do?

guest_ant
October 30, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,

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!

veena
November 01, 2007

# re: 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.

How can i do this?

shiva
November 02, 2007

# re: Downloading a File with a Save As Dialog in windows forms using C#.net

i want to download files in windows forms using C#.net,please tell me

Dhanapal
November 13, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

i need popup window action. it means i need confirmation the file is download or not.. any coding c#

Gokul Raj
November 20, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Response.TransmitFile is adding the .NET culture ID, if we override the InitializeCulture method of the page and set the page culture to en-US, when we open the file in client side, the content is prefixed with en-US. Do you have any idea how to turn off the culture getting embeded in the content. Thanks in advance

Bhavnik Gajjar
November 22, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi all,

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

Vegetarian Seahorse
November 29, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Good evening,

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.

Ramesh
November 30, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi All,
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..

Jason
December 10, 2007

# Showing Microsoft Documents in Popup Window

Erik,

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

suyash
December 11, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

hi,
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

Praveen
December 16, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,

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

DrGreenSticky
December 18, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Thank you, Rick! This was an excellent article!!! I appreciate all that you do.

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

Scott M
December 18, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Praveen,

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

Alex G
December 19, 2007

# Mobile devices

Hello,

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

Gene
December 19, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

Thanks, this is just what I was looking for.

madhu
December 20, 2007

# Downloading a xml File with a Save As Dialog in ASP.NET

Hi all,

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.

Alex G
December 20, 2007

# re: Mobile devices

I've found a work-around, for anyone who's interested: use a url rewrite module (or ISAPI filter) on the server to "fool" the mobile browser. The request should contain the desired filename, e.g. "http://example.com/example.mp3?1234", which will be intercepted by the request filter and transformed into "http://example.com/path/download.aspx?id=1234".

Hope it helps someone :)

Ashok
December 27, 2007

# re: Downloading a File with a Save As Dialog in ASP.NET

hi,
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

Xabatcha
January 02, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi there,
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 ;-) )

Simon Xin
January 10, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi rick, we store small a zip file in dataset in the session and output when users click on the link, but sometimes they cannot download the file correctly. the file download window will prompt up but then following the error message :

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(); 

Alv
January 13, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick,
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)

Rick Strahl
January 14, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

@Alv - you can't return more than one output from an HTTP request so if you need to download multiple files you have to combine them in some way like a Zip file. One Http response - one output.

greg
January 14, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

I have tried your codes and i can successfully do the download part for picture.. However i need it now to download a text file.. what codes do i ahve to ammend?

Prashant Vedpathak
January 15, 2008

# How to open Save As dialog Box without getting the first window containing Open,Save,Cancel,More info buttons.

Hi Mr Rick,

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

Sneha
January 16, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi ,

I have gone to your code.
It would be help ful if i get a complete code of it.

Thanks
Sneha

Prashant Vedpathak
January 17, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Place this code in ur button click event:

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

Denver Mike
January 26, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick,

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

Briankorobele
January 28, 2008

# Downloading a File from database using C#

hello Guys I am new in this world of programming ,this site is really hot and fun I have found so many solution for my projects. I was given task to develop A website that is supposed to Upload and Download from sqldatabase the Uploading part was easy the the challenge came when I try to Download from database

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

Santosh Singh
February 07, 2008

# Downloading a File with a Save As Dialog in Mobile

for mobile browser i used the following code :

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# .

Jay
February 13, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

hi Rick,
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.

Larry Smith
February 13, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Rick,
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.

Larry Smith
February 13, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Ok. Apparently my issue was caused by using the full url instead of getting the filename. And forget what I said about IE6/IE7. The following code works with both versions as well as Firefox:
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.

tappat p.
February 19, 2008

# HOW ZIP? Downloading a File with a Save As Dialog in ASP.NET

Great! Rick
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

rajan
February 24, 2008

# Downloading a File with a Save As Dialog in ASP.NET

i say , thanks 2 all

Robert
February 25, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi and thanks for very relevant stuff :)

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

NARESH
February 26, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi everybody,

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...

jithu
March 06, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Good Post

Eva
March 10, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi!
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!

Carl
March 18, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi, Rick.

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

Rick Strahl
March 18, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

@Carl - that's browser behavior and you can't change it. When you hit a download link and target to another frame that window will always open first and then the file will open and you're stuck with the window.

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.

Marvin
March 19, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hello Rick,

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

Marius
March 26, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

You can also do the following.

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

William F
April 08, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hello,
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,

jayas
April 09, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

hiii

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

Raghu
April 10, 2008

# problem in viewing MHTML report when it is Exported

Hi, I am facing a different problem when MHTML report is exported, this happens in alternatve requests, but when I save the file report is proper.The only problem is when I click on Open button , it pops another dialouge with



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

Rakesh
April 15, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi!
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.

mahesh
April 17, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

hi ,
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

ullas
April 23, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

How about the encording of file name?

Gopi
April 28, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi All,
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

sunder chhokar
May 01, 2008

# Want to view MHTML file in browser, unbale to view images of file in browser

Hi Rick,

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

sunder chhokar
May 01, 2008

# Want to view MHTML file in browser, unbale to view images of file in browser

Hi Rick,

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

ergolargo
May 13, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick

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

David
May 14, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,all

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

Sami
May 15, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi, all

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.

Ali
May 15, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,

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

Gopinath
May 18, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

hi everybody..... This is first time i meet you. I create a website with ASP.NET 2005, MS-ACCESS. In my website downloading part is very important. But i don't know how to do this. I need if the user click download button then the dialog box open for a path where to save the file. after the user select the path the file save to that path. also say how view that file in browser screen. Pllllllllzzzzzzzzz anybody help me. it's very urgent. Including mr.rick plz help me

Jason Smith
June 03, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

The code works perfectly, but is there a way that I can return the path that the user saved the file to. I want to log this information. Response.TransmitFile returns void. How could I go about tracking the path where the user has saved the file.

Thanks
Jason

Mar
June 03, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Rick,

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....

Al
June 11, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

wow bunch of dumbo's asking for solution, and not one of you was able to solve ur issue by urself and post the solution for others

Keith
June 11, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

I was attempting to stream text back to the browser (IE7) to be saved as a text file. It worked locally but not from the site that I deployed to. From the remote site, the 'Open/Save As' dialog did not open. Locally, the dialog would appear fine. After some trial and error, I figured out that the remote site needed to be added to the Trusted Sites list. After doing that, it worked fine. there is probably a security setting specific to this but this solved my problem.

Santanu Roy
June 13, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Thanx Rick, it is really a good solution !!!

John
June 13, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Some people add Response.AddHeader("Content-Length", content.Length.ToString) in their download code, whereas Rick did not. When is it required that you specify Content-Length yourself?

Rick Strahl
June 14, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Typically you don't to set content-length because ASP.NET buffers the output and automatically appends the content length because it knows before it ever sends the output (including TransmitFile) how big the content is.

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.

Olyvia
June 16, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

I am getting an error, Server cannot append header after HTTP headers have been sent.
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 + "'>&nbsp;");
}
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;
}

Pinky
June 23, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,
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. !!!

Matt Davis
June 30, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Some people have commented that Rick's solution does not work when there are AJAX update panels on the page. This is technically true but there is a get-around. For each file you could create a new aspx page and put Rick's code in the page load event of the life cycle. Then back on the page with the download link, you just call response.redirect(pagename.aspx)

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.

Matt Davis
June 30, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Also, it would probably be best to apend some stuff on the query string from the calling code - that way you could do this with just one page and also prevent people from stumbling across the page and getting the save as dialog popup..Again, this isn't ideal, but if you have to use AJAX update panels then it might be worth it.

manish singh
July 03, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

hi friends

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

stuart
July 08, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

brilliant. this was my first google search result, and fixed the exact problem I was having... thanks!

Dimitrije
July 10, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,

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

David Gutherz
July 10, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Man you're awesome, you don't have idea how mucho you helped me in my website hehehe, because of you i'll get my profesional diploma hehehe. Thanks!

Ravi
July 14, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick,

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

madhu
July 15, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

hai

i want to download a file from ftp directory? pls help? iwant to display download dialog box also.

madhu

Pankaja Shankar
July 16, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick,
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

shaban
July 18, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

To download without fire download save box use

Response.AddHeader "content-disposition","attachment; filename=fname.ext"

lalit
July 23, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

if facing exception..use this link

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);
.

Glenn Johnson
July 23, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick,

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.

Vivekanandan
August 04, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick,

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

Shoaib
August 07, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Use the following to hide Open button in Open/Save Dialog
<META name="DownloadOptions" content="noopen">
This would make the Open button invisible

zafar
August 18, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Thankyou guys for giving so much stuff on fileuploading. Its seems every one have an issue with FileUpload 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

tjhazel
August 20, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

I hate to beat a dead horse, but I am having an issue with Windows Media player. I have an httphandler I use to download mp3 files. User clicks the link and I am trying to prompt with file \ save as box. I cannot get around windows media player opening up.

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?

roji
August 29, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

i am facing an issue regarding downloading. i hosted my application in server machine and i try to attach file in client machine as it's attaching the file.But now the problem came while try to download it's not getting the file name.According to my knowledge the application can get the files only in server machine.As i need to solve this issue.while attaching itself is any way to take the client machine name or through the URl and save the attach file in server machine.


If anyone came across this sitution please help me.

Thanks,
Roji

Deepa
September 07, 2008

# Question: Downloading an image File with a Save As Dialog in ASP.NET

How to get Save As diaog box on a button click in asp.net to save the images,I want to save the infragistics chart that is in my web page??

Daniel
September 11, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

This works like a charm to download text base files:

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()

Raj
September 23, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi..
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"

Deniz
October 20, 2008

# Downloading a Office 2007 Document with a Save As Dialog in ASP.NET

Because no physical file operations where allowed I had to use a memorystream and Response.BinaryWrite() to return an Office 2007 Document.

I had to use
            Response.Clear()
            Response.ClearContent()
            Response.BufferOutput = True


Without 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

Erik Norman
October 28, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

I want to stream a dynamically generated PDF file to the browser.

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.

Sim
November 21, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,
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()

Aasf
December 07, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi All,

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.

Ali
December 18, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Artical is really good but doesnt provide a solution on a web farm.

Anyone likes to put a code for that. would be highly appriciated.

thanks a lot

Nir
December 22, 2008

# re: Downloading a File with a Save As Dialog in ASP.NET

Can we do the same in order to automatically prompt email the image?

Zafar Ullah
January 09, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

Aasf,

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

Anu V
January 30, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi, I have a linkbutton in a GridVeiw on my VB.NET webpage. This gridview is inside an AJAX Update Panel. I am using the below code to download a file whenever a link is clicked. it is not working but the file download works fine when i have the grid outside of an AJAX updatepanel. Any help would be grately appreciated. Thank you.

Response.Clear()
Response.ClearContent()
Response.ContentType = "application/octet-stream"
Response.AppendHeader("Content-Disposition", "attachment;filename=""" & MyDrawingFileName & """")
Response.TransmitFile(MyPath)
Response.End()

Ross Stensrud
January 30, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick and Community,

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

Shailja
February 05, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

I am facing while coding for downloading a xml file from the website i am working on. the code saves the xml which is created from a dataset but it donot show the save dialog box instead prints whole xml in the browser.

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();

Glauco
February 06, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

How can i show a message after the download?

lior
February 09, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,
Is there a way to set a default download directory and not display a Save As dialog?

Thanks,
Lior

Rick Strahl
February 09, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

A lot of people are asking the same question over and over: No - you can't control anything about where the file is going on the user's machine. You also can't display a message. You can only sent one response and that's the actual data. About the only thing you can do is direct the result to a new window and possibly - using Ajax - display some sort of message when the result is downloaded.

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.

lior
February 09, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

OK, Thanks.

Ashish Patel
February 09, 2009

# Configure Meta Tag At RunTime

when we use <META name="DownloadOptions" Content = "noopen" >

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.

David Terrie
February 09, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

One more gotcha: I had code using
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.

Abhishek
February 11, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

Thanks Rick, That's what i was looking for.

Tommy Schouw Rasmussen
February 13, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

I had an issue with a datagrid where each row had an export to excel feature attached. When we dumped it into an updatepanel, it ofcourse broke.

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.

Abhijit Parkhi
February 24, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick.

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

Swetha
March 25, 2009

# re: Downloading a XLS File with a Save As Dialog in ASP.NET

Hi Rick,
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...

Nik
April 17, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

For those who have problem with downloading file on production/staging servers (the file is corrupt) use the code below. I was trying to figure out what was going on for hours without success. The question was asked here quite a few times with no answer. So I just started looking for a work around. Here it is:

 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

Nik
April 17, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

I just wanted to add that this issue with the garbled/corrupted files after download is permissions issue.
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

Rick Strahl
April 17, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

@Nik- I don't think it's neccessary to get the fileinfo correct. The trick is to ensure that the filename is fully qualified and that the file exists and that your app has permissions to read the file from disk.

Pablo
April 20, 2009

# how to secure download?

Hi Rick, I've found very usefull you post. My question is how to provide security in download process? . I have critical pdf files created on the fly and then the asp page sends to download, but and I dont want someone else get the file using a sniffer or something to hack the file transmition.

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

Rick Strahl
April 20, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

@Pablo - why not do the easy thing and use SSL? SSL is transparent to your application and your users so no changes are required. Any other kind of encryption will require you to have something running on the client side that can decrypt data.

Raja
May 06, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi..
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

amoncarter
May 27, 2009

# re: Uploading a File with a Open in ASP.NET

Hi Rick

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

Brent
May 28, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

Great posting! Very useful. Thank you.

Brent

srinivas
June 01, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,

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..

satish
June 09, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

this site is awesome ..it helped me out a lot ..
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

david Denman
July 15, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

So I this code for prompting for the download of a word doc. On my development computer it works wonderfully. When I upload it to the server it stops working. I don't receive and errors and I'm not prompted with the download dialog box. Any idea?

            Response.ContentType = "application/ms-word"

            Response.AppendHeader("Content-Disposition", "attachment; filename=InstituteBadge2Done.doc")

            Response.TransmitFile(Server.MapPath("InstituteBadge2done.doc"))

            Response.End()

Kevin
September 11, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

I have one problem with sending files to the browser for download, and I cannot seem to fix it.
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.

KC
September 23, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Guys,

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

sanjana
October 09, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi,
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...

daw
October 15, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

hi..

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,

Jyothi
November 17, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick,

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

geoff
December 02, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

I have the following code to download a file for a user but I'm running into a problem where the filesize is not being reported to the browser so it never completes the download. The filesize is around 99mb but the browser will continue to download well past 100mb. Is there a way to specify how large the file is when initiating the download so it completes correctly? Here's my code. Thanks.

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();

geoff
December 02, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

I found that adding the following code resolved the file size problem.

Response.AddHeader("Content-Length", size.ToString());

Rick Strahl
December 02, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

@Geoff - that shouldn't be necessary. I think the Response.Flush() is what's causing the content-length to not be sent. Remove that and you shouldn't need to specify the content-length manually.

pawan
December 03, 2009

# re: Downloading a File with a Save As Dialog in ASP.NET

Hi Rick,
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

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024