Download PDF in ASP Error on Some Machines - asp.net

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

Related

Writing table contents to xls from vb.net

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.

How to download CSV in ASP.Net VB - Used to work Has stopped working

I'm trying this.
Response.Clear()
Response.ContentType = "text/csv"
Response.AppendHeader("Content-Disposition", "attachment; filename=" & strFile)
Response.Flush()
Response.End()
where strFile is AllSites_21Aug2014_145914.csv
on a web page called MicadDataCSV.aspx?SessID=1
but what is offered to download is MicadDataCSV_aspx?SessID=1
NB this worked a week or two ago and has stopped working now.
I couldn't find any explanation of why this was happening, but in the end just tried the fingers crossed hope this works re boot, which thankfully it did.
I still don't know what caused this problem, let alone preventing it happening again, so not good, but enough.
Try:
Response.AppendHeader("Content-Disposition", "attachment; filename=" & Server.HtmlEncode(strFile))

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"

Downloading pictures/Word documents using 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!

Resources