Chronos
Chronos

Reputation: 119

C# .net Writing Content from POST Request as PDF Producing blank PDF

I'm handling POST requests that include a PDF and am trying to re-construct the file and save it to the server on my end. Here's the code I'm using for that, pdfString is from the request body:

string myPath = @"C:\mypath\mypdf.pdf";

byte[] byteArray = Encoding.UTF8.GetBytes(pdfString);

MemoryStream stream = new MemoryStream(byteArray);
using (var writeStream = File.OpenWrite(myPath)) 
{
     stream.CopyTo(writeStream);
     writeStream.Close();
}

This gives me a file that is the correct size and number of pages as compared to the original, but all of the pages are blank.

In case this is useful, here is the beginning of the request body where some of the PDF's meta data looks to be stored:

Content-Disposition: form-data; name="file"

%PDF-1.3
%          
%100230[584]
1 0 obj 
<<
/Filter/Standard
/R 2 /V 1
/O<ad6a15e8126b8f8185e4db64f2a41b8bd94a79eed4f6fd1e6b17da57ea2d8ba9>
/U<e1f8eabd02255525f1eb0c68575189d08e577035a6905adeb50d84e67779a066>
/P 4
>> 
endobj
2 0 obj 
<<
/Producer(sZT\310]!\354w\244\214)
/Author(zS[\315D\002\332\005\252\263\b$\375f]\334)
/Title()
/Subject(\007\004\017\233\0260\203g\205\260\016/\375`J\324x"8v)
/Keywords()
/CreationDate(t\014\017\233\007T\222\024\330\346Qr\2539\037\210)
/ModDate(t\014\017\233\007T\222\024\330\346Qr\250=\033\214)
/Creator(Gfy\355\026\005\332\005\236\257"7\371lK\230[o\bZ)
>> 
endobj
3 0 obj 
<<
/Type/XObject/Subtype/Image
/Name/wpt1
/Width 640
/Height 480
/BitsPerComponent 8
/ColorSpace/DeviceRGB
/Length 23713
/Filter [/FlateDecode/DCTDecode] >>

Nothing after that is plain-text. Until the PDF is closed.

Is there some other way to read the request into memory that I should be using or something?

Upvotes: 2

Views: 697

Answers (1)

JDwyer
JDwyer

Reputation: 844

I don't think you want to be treating it as UTF8 data. You probably just want to get a stream directly from the request. See: http://msdn.microsoft.com/en-us/library/d4cek6cc(v=vs.110).aspx

using (var reqStream = req.GetRequestStream()) 
{    
  // reqStream.Write( ... ) // write the bytes of the file
  // or stream.CopyTo(writeStream);
}

Check Request.Files http://msdn.microsoft.com/en-us/library/system.web.httprequest.files(v=vs.110).aspx for multipart/form-data.

Upvotes: 2

Related Questions