Classic ASP - Strange Characters Instead of PNG - asp-classic

I'm using http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Query_View_with_a_Preview_Image%3FTocPath%3DAPI%2520Reference%7C_____43 to output some PNG files.
The last bit of the code is
postResponse = httpRequest.ResponseText
Response.ContentType = "image/png"
response.BinaryWrite postResponse
This results in
ÿÿPNG
Any advice? I've tried replacing BinaryWrite with just Write and get
ï¿¿PNG

try using the following:
response.BinaryWrite httpRequest.responseBody

Related

Getting a corrupted XLSX file when writing it to Response.OutputStream

In ASP.Net, I'm using NPOI to write save to an Excel doc and I've just moved to version 2+. It worked fine writing to xls but switching to xlsx is a little more challenging. My new and improved code is adding lots of NUL characters to the output file.
The result is that Excel complains that there is "a problem with some content" and do I want them to try to recover?
Here is a pic of the xlsx file that was created from my Hex editor:
BadXlsxHexImage Those 00s go on for several pages. I literally deleted those in the editor until the file opened without an error.
Why does this code add so many NULs to this file??
using (var exportData = new MemoryStream())
{
workbook.Write(exportData);
byte[] buf = exportData.GetBuffer();
string saveAsFileName = sFileName + ".xlsx";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}; size={1}", saveAsFileName, buf.Length.ToString()));
Response.Clear();
Response.OutputStream.Write(buf, 0, buf.Length);
exportData.Close();
Response.BufferOutput = true;
Response.Flush();
Response.Close();
}
(I've already tried BinaryWrite in place of OutputStream.Write, Response.End in place of Response.Close, and setting Content-Length with the length of the buffer. Also, none of this was an issue writing to xls.)
The reason you are getting a bunch of null bytes is because you are using GetBuffer on the MemoryStream. This will return the entire allocated internal buffer array, which will include unused bytes that are beyond the end of the data if the buffer is not completely full. If you want to get just the data in the buffer (which you definitely do), then you should use ToArray instead.
That being said, why are you writing to a MemoryStream at all? You already have a stream to write to: the OutputStream. Just write the workbook directly to that.
Try it like this:
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", saveAsFileName));
workbook.Write(Response.OutputStream);
Response.Flush();
Response.Close();

set default name to PDF document with itextsharp

i am sending a PDF to my page and i want to set a default name when the user tries to save the PDF document.
i am using ItextSharp and VB.Net
Using s As MemoryStream = New MemoryStream()
Dim Pdf_Writer As PdfWriter = PdfWriter.GetInstance(DocumentPDF, s)
DocumentPDF.Open()
DocumentPDF.SetMargins(10.0F, 10.0F, 10.0F, 10.0F)
DocumentPDF.Add(Table)
DocumentPDF.Close()
contentX= s.ToArray()
HttpContext.Current.Response.Buffer = False
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.ClearHeaders()
HttpContext.Current.Response.ContentType = "Application/pdf"
HttpContext.Current.Response.BinaryWrite(contentX)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
End Using
.
Response.AddHeader("content-disposition", #"attachment;filename=""MyFile.pdf""");
this way download the file(yea, it sets a default name), but i just want to show the file and if the user wants to save it, well... save it(with a default name)
how can i set a default name to my PDF document?
try with this code:
Response.ContentType = "application/pdf"
Response.AppendHeader("Content-Disposition", "inline; filename="filename".pdf")
Response.TransmitFile("filename")
Response.End()
I had a similar problem delivering a PDF via a handler page (.ashx). No matter what I set in the HTTP headers, saving from the browser PDF reader would always set the filename to "getpdf.pdf" when I used this url.
http://www.thepdfchef.com/handlers/getpdf.ashx?id=5188p
So what I did was add an escaped string after the handler path then the querystring at the end of that, like so:
http://www.thepdfchef.com/handlers/getpdf.ashx/Wellbeing%20And%20Domestic%20Assistance%20From%20John%20Paul?id=5188p
You should check for invalid characters and strip out any that could cause the name to be dangerous.

File fetch from database using asp

I am storing some the binary data for some files in a database (yes, I know this can be a bad idea). I am able to get the files out, with the correct content type, since I have stored it. But I'm having trouble getting the file to the client with the right filename. Right now I have the following code in a file called get_file.asp:
sSQL = "SELECT filename, contenttype, binarydata FROM new_attachment WHERE filename = '" & filename & "'"
oRs.Open sSQL, conn, 3, 3
If Not oRs.EOF Then
Response.ContentType = oRs(1)
Response.BinaryWrite oRs(2)
End if
This will return files correctly, but with the filename of 'get_file.asp', instead of, say, 'myfile.txt'. The url visited is .../get_file.asp?filename=myfile.txt.
Is there a way I could change the name of the file when the browsers prompts the user to save it somewhere?
You need to send out the correct header:
Response.ContentType = "text/html"
Response.AddHeader "Content-Disposition", "attachment; filename=YOURFILE.TXT"
You need to add a Content-Disposition header.
The header should look like this:
Content-Disposition: attachment; filename=<name of file>
Side note: The way you are concatenating SQL is open to SQL Injection - you should be using parameters.

Export to Excel file as .zip to reduce file size. How to compress xmldata before sending it to the client?

I like to compress the xmldata before the data is provided to the client as an excel file. I am trying to compress and deliver it as a .zip file. its not working Here's my code below. Please help
I tried compressing it, converting it to bytes etc etc. The issue with below code is, the XSL transformation is not happening properly and the output excel file is raw xml with some .net exception at the end. (that's what I see on the .xls file that's downloaded at the end)
Before I started working on compression my below code was working fine that gives properly formatted excel file from the xml input. the excel file is so nice you can't even tell it was from XML.
pLEASE HELP with compression
Dim attachment As String = "attachment; filename=DataDownload.xls"
Response.ClearContent()
Response.AddHeader("content-disposition", attachment)
Response.ContentType = "application/vnd.ms-excel"
'Response.ContentType = "text/csv"
Response.Charset = ""
Dim ds As New DataSet()
Dim objXMLReader As XmlReader
objXMLReader = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteXmlReader(ConnectionString, CommandType.StoredProcedure, "SPName")
ds.ReadXml(objXMLReader)
Dim xdd As New XmlDataDocument(ds)
Dim xt As New XslCompiledTransform()
'xt.Transform(xdd, Nothing, Response.OutputStream)
Dim bytearr() As Byte
bytearr = System.Text.Encoding.Default.GetBytes(xdd.OuterXml)
Dim objMemStream As New MemoryStream()
objMemStream.Write(bytearr, 0, bytearr.Length)
objMemStream.WriteTo(Response.OutputStream)
xt.Transform(xdd, Nothing, Response.OutputStream)
Response.End()
Why you don't use XLSX-Format instead of XLS? It is already XML-Data compressed in a ZIP file. You can rename a XLSX file to ZIP to verify this.
Updated: By the way, ContentType in the case should be "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" instead of "application/vnd.ms-excel".

File does not begin with '%PDF-'

I am exporting the HTML Content to PDF.
System.IO.StringWriter sWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(sWriter);
Response.Buffer = true;
FormId.RenderControl(htmlWriter);
Response.ContentType = "application/pdf";
// Added appropriate headers
Response.AddHeader("Content-Disposition", "inline; filename=XXX.pdf");
Response.AddHeader("Content-Length", htmlWriter.ToString().Length.ToString());
Response.Output.Write(sWriter.ToString());
Response.Flush();
Response.Close();
FormId is my Div past of the content..
I am getting the error as "File does not begin with '%PDF-'"
I have included Response.clear(); The output is not coming
You're rendering out the html (div as you said) before the pdf in the output stream, so the two are combined. That's causing any app looking at the output to interpret it as a corrupted file. I'd try removing the first two lines:
Response.Buffer = true;
FormId.RenderControl(htmlWriter);
If that doesn't solve the issue, add a Response.Clear() call before everything.
This is all assuming sWriter contains the PDF at the beginning of this code block -- if not, a little more context might be helpful.
Some advice: if at all possible, move this out of the page to a .ashx or other IHttpHandler.
I was facing the same issue while writing some HTML content to PDF.
I finally found that invalid HTML content causes this issue.
For example, <ul> tag without closing tag </ul>.
Once I put in the proper closing tags, it works fine!
Do a Response.Clear() before starting to stream your output.

Resources