Amazon S3 - MS office files corrupted when downloading - c#

When I upload a docx, xlsx or pptx to amazon S3 using aws .net sdk the file is getting uploaded fine and I am able to view the file directly from S3 without any issues. But when I download the file in ASP.net using C# I am getting a warning message (see below) when opening the file:
"Excel found unreadable content in test.xlsx. Do you want to recover the contents of this workbook?" If I click yes, I am able to see all the contents in the document.
similarly I am getting a warning message for .docx file as well.
This is the C# code I am using:
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.OutputStream.Write(Content, 0, Content.Length);
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
Update: When I download the file in windows forms app it is working fine and the problem is with web app only.
What am I doing wrong?
Please help...

More information is needed to figure this out. The code snippet you provided looks OK. The problem looks to be elsewhere in your code... For example, what are you loading inside "Content"?
Also, it would help if you tried uploading and downloading a simple text file, to see what kind of data gets appended.

If Content is a byte[] created from a MemoryStream, make sure you're calling .ToArray() and not .GetBuffer() to get it. If you use .GetBuffer(), you'll potentially get extra bytes on the end, which the office file format probably doesn't like. Your other file types you've tried it with might be more tolerant of extra data they weren't expecting on the end.

Related

Outputting .RTF file to response Corrupt

I have an AJAX file uploader on my page, and use this to store various different file types into a database, However when I store a .rtf file and then try to output this using response, I get a file corrupt and cannot be opened error message. The file uploader automatically detects the mime type of the file on upload and stores the file as "application/msword" as this didn't work I tried giving it several other mime types however none of them worked.
Does anyone know of any reasons why this file may be corrupt?
PS. I have also tried uploading several different .rtf files with text, no text and images, etc. however none of them worked. output code below:
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = displayFile.MimeType;
context.Response.AddHeader("content-disposition", "attachment; filename=" + displayFile.FileName);
context.Response.BinaryWrite(displayFile.Data);
context.Response.End();

Generating pdf using generic handler (ashx)

I got a requirement to create pdf on the fly from the data stored in database.
I am using html, jquery and WCF in my application.
I don't find a way to generate pdf (Show in a browser or as an attachment) using client technology (jquery, or any other client plugins). I tried to use pdf.js, but could not able to succeed. Later I used .net generic handler to generate pdf. I was passing bytearray to handler, in turn pdf started rendering on client.
I got some random issue, then I wrote a sample application to make sure handler is working fine. I used same code with a static text to generate pdf, but it started throwing a error on the client.
Below is the code snippet I used
context.Response.Clear();
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("content-disposition", "inline; filename=download");
context.Response.Write("Hello World");
//context.Response.BinaryWrite(System.Text.Encoding.Default.GetBytes("Hello world"));
//context.Response.BinaryWrite(System.Text.Encoding.UTF8.GetBytes("Hello world"));
context.Response.Flush();
context.Response.End();
I am getting errors on all the browsers
Failed to load pdf document on Chrome.
An error occurred while loading the PDF. PDF.js v0.8.505 (build: da1c944) Message: InvalidPDFException - In mozilla firefox
File does not begin with '%PDF-' in IE.
Note: I tried with aspx page too. I cant create physical file due security issues. If there is any better way of achieving it please let me know. Thanks in advance.
PDF is a standard file format.You cannot write a normal text file and rename it to filename.pdf and wish it to work.
You will need .Net libraries for that.There are lot try googling .Net pdf library
Some Info.
pdf.js is just for viewing in browser.
setting context.Response.ContentType just tells the browser the file its gonna receive,So it can use existing mapped application to open it.Like Adobe browser plugin for pdf file.

Response.TransmitFile corrupting file

I have a file on my server or well in this localhost. I want to transmit it to user using this code:
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=buylist.pdf");
Response.TransmitFile(Server.MapPath("~/buylist.pdf"));
Response.ContentType = "application/csv";
Response.AppendHeader("Content-Disposition", "attachment; filename=buylist.csv");
Response.TransmitFile(Server.MapPath("~/buylist.csv"));
I know the file I am trying to transmit our fine and I even tried adding Response.Close() but each time the file is corrupted. The csv give me the page's HTML. I am really lost.
Try putting a Response.Clear() at the top of this code, and a Response.End() and bottom.
Also, it looks like you're trying to transmit two files in one response, and that just won't work. It might also be two versions of the code showing in the same snippet in your question, but this is still worth mentioning: You need to pick one file to return in one response. If you absolutely must return two files at once, you'll have to zip or tar them together first. There is no way to send two files with the same response.

How should I be saving .doc documents to a SQL Server database

I am saving a .doc file to a SQL Server database as varbinary(max) using the C# code below.
I am able to save the file, but when I retrieve the file back and want to display the contents on the web page, my code is downloading the file and I am in great confusion about how to handle it.
The exact functionality I am looking for is the way naukri.com uploads the resume and gives a preview of it. My code is :
byte[] fileContent = new byte[fuResume.PostedFile.ContentLength];
fuResume.PostedFile.InputStream.Read(fileContent, 0, fuResume.PostedFile.ContentLength);
//lblAppliedMessage.Text = ByteArrayToString(fileContent);
//lblAppliedMessage.Text = BitConverter.ToString(fileContent).Replace("-", string.Empty);
byte[] btYourDoc;
btYourDoc = fileContent;
Response.ContentType = "application/ms-word";
Response.AddHeader("Content-Disposition", "inline;filename=yourfilename.doc");
Response.OutputStream.Write(btYourDoc, 0, fileContent.Length);
Response.BinaryWrite(btYourDoc);
Response.End();
The reason your file is getting downloaded instead of displayed is because you're setting the content type to application/ms-word. This tells a browser to download the file (they can't natively handle files of that type so they delegate to an external app).
You'll need to have code that knows how to interpret the MS Word format and convert that to something viewable in a browser (HTML, some kind of plugin that will do that for you, etc). Saving the raw Word document and then sending it back to the client in the same state is basically just having them download a Word file.
squillman is right. There are tons of third party components that do Word -> HTML conversion.
One other option, which may be more appropriate for an intranet site, is to install Word on the server.
An example of this is here:
http://www.c-sharpcorner.com/UploadFile/munnamax/WordToHtml03252007065157AM/WordToHtml.aspx
Effectively, the doc is opened, saved out as HTML, then subsequent requests can retrieve the HTML version of the file for preview.
Office automation server side has many pitfalls, however - see http://support.microsoft.com/kb/257757 for more information.
Here's a good one where the end result it's up to the user whether to download or view the file here's the link but #Squillman is right by putting the Response headers you're telling it to download.

Folder Browser Dialog Box in ASP.Net

I've created a word document generator in C sharp and I want that generated word document to be save in a specific place in the client. I'm looking for a similar functionality like FolderBrowserDialog in Windows Form. I'm using ASP.Net and I tried may solutions but still no luck. Anyone can help me.
No! server (web-app) program don't have an ability to save a generated document at specific place at client.
try to use the HttpResponse in behind's code:
like:
// Clear the content of the response
Response.ClearContent();
// Add the file name and attachment, which will force the open/cancel/save dialog box to show, to the header
Response.AddHeader("Content-Disposition", "attachment; filename=" + savedNameWithExtension);
// Add the file size into the response header
Response.AddHeader("Content-Length", myfile.Length.ToString());
// Set the ContentType
Response.ContentType = ReturnExtension(myfile.Extension.ToLower());
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
Response.TransmitFile(myfile.FullName);
// End the response
Response.End();
This section of code will prompt the user to save the specified file on a certain location on his machine.
Hope this is clear.
When you download a file from the browser its the browser to show the save file dialog and this works on all browsers and on all platforms. Just keep the default behavior and let users decide location and file name. I guess any hacky implementation of that part if possible at all, it is likely to break in some browsers or platforms, like mac, ipad, android...
you do not need to specify any control to be used, once you call the methods to download a file like
Response.WriteFile or Response.BinaryWrite or any other, the browser takes care of everything else for you and let it be like that ;-)

Categories