Getting jibberish when attempting to open DOCX in a browser - asp.net

Using a memory stream & the correct MIME type with Response.ContentType. Special characters are displayed instead of prompting to open a Word document. I'm using:
using (MemoryStream ms = new MemoryStream())
{
doc.SaveAs(ms);
Response.Clear();
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
ms.WriteTo(Response.OutputStream);
Response.End();
}
Here's an example of the output I get now rather than a prompt to open a Word document:

Turns out it was not a MIME or Response.ContentType issue at all. Being an MVC application, I was attempting to open the FileResult in a modal. Copy/Paste fail, as other buttons worked this way to display content. Not a Word document!

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.

Inline ReportViewer PDF cant open hyperlinks in new window

I have a old report generated by ReportViewer in a webpage (Asp.Net). Changed so it's possible to genererate the report as a inline PDF in the same window via:
byte[] bytes = Master.ReportViewer.LocalReport.Render(
"PDF", deviceInfo, out mimeType, out encoding,
out extension,
out streamids, out warnings);
Response.ClearHeaders();
Response.ClearContent();
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("Content-Disposition", "inline; filename=Report." + extension);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
Purpose: Large reports tend to make the webpage unresponsive. The inline PDF don't have the same problem.
Problem: Hyperlinks can only open in the same window.
Anyone had the same problem? or has a simple solution?
How is your link look like?
Did you set up target of your hyperlink to "_blank"?

Why cant opened downloaded docx files ,in asp.net?

I try to download a docx file from serverside.
What is my wrong ?
this is code :
FileInfo file = new FileInfo(filepath);
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AppendHeader("Content-Disposition", "attachment; filename = " + ((Button)sender).CommandName + ".docx");
Response.AppendHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
Response.End();
I have posted something similar in another question for an PDF but here goes. It's much easier to stream this sort of data back through an ASHX handler.
Something like what I posted in this question but with a docx file.
Display PDF in iframe
It looks like you are using a normal ASP.NET page and are trying to modify the standard behavior by clearing out the headers, etc. You won't have to fiddle with the headers or anything like that with an ashx handler.

How do I create an XML file with ASP.NET and have it prompt to download?

I'm currently trying to write data (client machine) into a xml file where the user can save. However, I want the users to be able to decide on where they want to save this written xml file. Is there any controls or codes that I can use to allow the users to save the file?.
Update:
is that right way to do?
**HttpContext.Current.Response.Write(xw.ToStroing()); <<< ??????**
HttpContext.Current.Response.End();
update:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
MemoryStream ms = new MemoryStream();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.AddHeader("Content-Disposition:", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
using (StringWriter sw = new StringWriter())
{
using (XmlWriter xw = XmlWriter.Create(ms, settings))
{
xw.WriteStartDocument();
xw.WriteStartElement("Name");
xw.WriteStartElement("Application");
................
......................
HttpContext.Current.Response.Write(xw.ToStroing());
HttpContext.Current.Response.End();
When you begin a file download, the client's browser will handle the file saving location.
If you want to force the file to download instead of open, add this HTTP header to your response:
Content-Disposition: attachment; filename="myFile.xml"
here is the link helps me :)
Where is the MemoryStream being used? You should pass the StringWriter to the XmlTextWriter constructor then Response.Write() the contents of the StringWriter
Add this after the Response.AddHeader line:
Response.ContentType = "application/octet-stream";
This will force download of files, regardless the file type.

Resources