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"
Related
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().
I am having a user who is reporting that files are being displayed as raw data in his browser. He uses Internet Explorer.
The files are being served via a .ashx handler file and it has been working until.
This is the relevant part of my .ashx handler:
context.Response.Clear()
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name)
context.Response.AppendHeader("Content-Length", size.ToString)
context.Response.ContentType = "application/pdf"
context.Response.TransmitFile(fullname)
context.Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
Can anyone figure something out of this screenshot?
Update: this behaviour appears on Windows 10 when running either IE 11 or Edge and only the second time a file is being opened. It happens for both .pdf and .docx files.
This is the code I use to stream PDFs to a client. It works in IE 11. The main difference is that I am using BinaryWrite which based on your code, you may not want to do..
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf");
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName + ".pdf");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.End();
There might be a solution here
I'll like this as well just in case..
According to this thread, it could be as simple as replacing Response.Close with Response.End (or in your case.. adding)
I finally found the answer myself - it had to do with the HTTP header content-length which i mistakenly submitted with a value exactly 1byte too large.
This caused the strange behavior in only IE/Edge and only Windows 10 as described in the OP.
I had the same problem with an aspx page that transmits file to browser in Page_Load event handler.
My mistake was an absense of
Response.End();
method call. When I added this line the problem has gone.
I have a program with an option to write db contents to an excel spreadsheet. This functionality is contained on a page called 'Search_aspx'.
Response.ClearContent()
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("Content-Disposition", "attachment; filename=FileName.xls")
Response.Cache.SetCacheability(HttpCacheability.Private)
Dim dg As New DataGrid
dg.DataSource = dtResults
dg.DataBind()
Dim sw As New System.IO.StringWriter()
Dim htw As New HtmlTextWriter(sw)
dg.RenderControl(htw)
Response.Write(sw.ToString)
Response.Flush()
Response.Close()
This worked fine forever, but last week I migrated the solution to a new server (Server03 to Server08), and now it is not working. When I try to save, it asks if I want to "Save search_aspx" instead of "Save FileName.xls".
What is the issue here?
EDIT:
All righty... I took the advice posted below and followed Mason's suggestion, and the page still asks if I want to save 'Search_aspx'. Now have EPPlus installed in my solution, properly referenced etc....
Response.ClearContent()
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("Content-Disposition", "attachment; filename=FileName.xlsx")
Dim package As New ExcelPackage()
Dim sheet = package.Workbook.Worksheets.Add("Data")
sheet.Cells.LoadFromDataTable(dtResults, False)
Response.BinaryWrite(package.GetAsByteArray())
Response.Flush()
Response.Close()
The real issue is you aren't creating an XLS file. You're creating an HTML file with a .xls extension. I discuss several reasons why that's a bad idea and go into detail about what you can do instead on my blog.
The short and sweet version is that there's no good way practice to generate a .xls file in an ASP.NET environment, and you should either generate .xlsx files with a decent library (discussed on my blog) or switch to another data format such as CSV.
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.
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!