Downloading pictures/Word documents using ASP.NET - asp.net

If I put the following code:
Response.ContentType = "image/jpeg"
Response.AppendHeader("Content-Disposition", "attachment; filename=capitol.jpg")
Response.WriteFile(MapPath("capitol.jpg"))
into Page_Load, I will get the dialog box to download the image. But when I put the same code into a sub routine:
Private Sub downloadPic()
MsgBox("Hello!")
Response.ContentType = "image/jpeg"
Response.AppendHeader("Content-Disposition", "attachment; filename=capitol.jpg")
Response.WriteFile(Server.MapPath("capitol.jpg"))
Response.End()
End Sub
I get the MsgBox (just for testing) but I don't get the ability to download the image. Any ideas?

You can't output to the page and also push the download content within a single request/response.
Anyway your code won't work properly with a Response.Clear() before assigning header and WriteFile.

Thank you for the comment. The problem with my code was that I had the WriteFile code within an UpdatePanel. That was my mistake!

Related

Download PDF in ASP Error on Some Machines

I am using this code to generate pdf's to download on an ASP page and the pdf does download properly on some pages but not on all. Several users are experiencing an error message as seen in the attached image. Please let me know if you have suggestions on how to fix this problem. It is sporadic so its been hard to nail down a cause.
Public Sub Download(filename As String)
Response.Clear()
Response.BufferOutput = False
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment; filename=" + Path.GetFileName(filename))
Response.WriteFile(filename)
Response.Close()
End Sub
Try Response.Flush(), followed by Response.End().

Response Redirect not working after sending email

I have a code that works with EPPlus library to modify some data from a dt to an excel file that it attachs itself and sends an email, and also downloads that file to the client sending it.
However from the following onClick method, it doesnt do anything but the SendModFile(), i think the text and stuff needs a postback thats why its not changing, that i can take away, but i must disable the button for the process not to send more than one email and redirect to the main menu, how can i acomplish this.
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Label1.Visible = True
Button2.Enabled = False
Label1.Text = "Sending..."
SendModFile()
Label1.Text = "Sent"
Response.Redirect("~/Main.aspx")
End Sub
Edit:
This is the end of the SendModFile() that lets download the file after sending the email, is there a way to optimize this, i believe this part is the one messing up due to Response.End()
Response.Clear()
Response.Buffer = True
Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AppendHeader("content-disposition", "attachment; filename=ExcelFileName.xlsx")
Response.BinaryWrite(memStream2.ToArray())
Response.End()
When you call Response.End, that's the end of the response. You can't then do a redirect.
One workaround is to have the user download the file in a separate HTTP request by providing a link or button that downloads the file, so that you still main control over the page they're accessing.

No response in postback after writing binary to the response

Requirement:
I want to download a file (*.docx) on the click of a button, first I read the bytes of the file, then I write the bytes to the response, this works fine and I have used this code several times before, but I am getting this weird behavior where the code executes successfully, without exceptions, but there is no response being sent back to the client (nothing happens, no response, no file download), furthermore, if I put the code in Page_Load event, the code works flawlessly, it only does not work in the button click event(i.e. on postbacks), here is the code that I am using:
Dim arrBytes() = File.ReadAllBytes(strFilePath)
Response.ClearHeaders()
Response.ContentType = "application/octet-stream"
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=test.docx")
Response.AddHeader("Content-Length", arrBytes.Length.ToString())
Response.BinaryWrite(arrBytes)
Response.Flush()
Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
Any help is much appreciated.
EDIT:
I tried 'Response.WriteFile instead ofResponse.BinaryWrite and Response.End instead of ApplicationInstance.CompleteRequest but nothing succeeded.
Turns out there was an UpdatePanel in the MasterPage, the problem was solved when I registered the button as a post back control ... That hurts I know.
So I solved it by using this line of code in the Page_Load event:
ScriptManager.GetCurrent(Me).RegisterPostBackControl(btnSubmit)

Excel file showing aspx page after download from web folder

I am using the following code to download an excel file from my asp.net/vb.net website:
Dim msFilePath As String
Dim msFileName As String
msFilePath = Server.MapPath("~/Template.xls")
msFileName = msFilePath
Dim mAttachFileName As String = "Template.xls"
Response.Clear()
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("Content-Disposition", "attachment; filename=""" & mAttachFileName & """")
Response.Flush()
The excel file is a template being provided with column headings and that is all it contains. When I click on the download button in my website it prompts me to save/open the file with the correct name 'Template.xls'. Once I open it is displaying the aspx page inside the excel file instead of the data that is supposed to be in the file and giving me an error saying it is missing the css file. I have debugged through and the path is pointing to the correct location of the file so I'm not sure what is causing the problem. Any help appreciated!!
I've had exactly the same problem, I'd like to tell why yours doesn't work but i'm not that smart. Instead i'll just tell you what code i've used that now works for me:
replace
Response.AddHeader("Content-Disposition", "attachment; filename=""" & mAttachFileName & """")
Response.Flush()
with
Response.AppendHeader("Content-Disposition", "attachment; filename=""" & mAttachFileName & """")
Response.TransmitFile(FilePath)
Response.End()
I know that response.End() is deprecated but without it I always get all that html garbage...
I suddenly started having the problem in my machine. I tried the application in other machines (web app) and it worked. I had to rule out coding issues at that point. I tried a million things and nothing worked. I rebooted the machine and voila...it worked.
Rebooting is always my last option, believe me.

Error in file after download

I have word document which is opening perfectly at server but when i download it using button click event of my website it gets currept.
i am using below code on button click to make document download.
please help to resolve this problem:
i am using .net framework 3.5
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=StandardLetter" + _responseId.ToString() + ".doc");
Response.ContentType = "application/octet-stream";
Response.TransmitFile (Server.MapPath("~/document/letter/StandardLetter" + _responseId.ToString() + ".doc"));
Do you have a Response.End() after that code you posted? If not, you will get extra "html" code from the aspx file added to the transmitted file - thus corrupting it.
EDIT
As Akshay Anand mentioned, a better way would be to call HttpContext.Current.ApplicationInstance.CompleteRequest(); instead of Response.End() see docs. See also this question.
Ok well here is the code I use, it's vb but easily converted ;)
Response.ContentType = "application/pdf"
Dim byteArray As Byte() = File.ReadAllBytes(MergedFile)
Response.AddHeader("Content-Disposition", "attachment;filename=""" & ShortFilename & """")
Response.AddHeader("Content-Length", byteArray.Length)
Response.BinaryWrite(byteArray)
Response.Flush()
Response.End()
This works for PDF and by changing .ContentType to Excel spits that out too.. So I assume this will take any MIME type. Good luck!
I take my pdf document called MergedFile and convert it to a byte(), I give it a 'ShortName' that can be entered by the user. Content-Length is very important..
Instead try:
Response.ContentType ="application/msword";
I dont use Word but for Excel I use:
Response.ContentType = "application/x-msexcel"

Resources