0

I'm building an ASP.NET Core Web API in C#. I receive a PDF file in the request body.

When I write the bytes of the request body, I get a file having base64 string (which should be decoded to get the actual PDF).

I don't know what to do next .. please advise ..

var ms = new MemoryStream((int)Request.ContentLength);
req.CopyToAsync(ms).GetAwaiter().GetResult();
System.IO.File.WriteAllBytes("test.pdf", ms.ToArray());

When I open test.pdf, I get something like the below:

JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBl............cnR4cmVmDQoxODkzOQ0KJSVFT0Y=
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
mamhh
  • 85
  • 1
  • 9
  • Does this answer your question? [How do I encode and decode a base64 string?](https://stackoverflow.com/questions/11743160/how-do-i-encode-and-decode-a-base64-string) – Russ Dec 29 '20 at 21:16
  • NO. It didn't work for me. let's say, for example, that I want to write those bytes to a file and get a valid PDF file. what should I do ? – mamhh Dec 29 '20 at 21:22
  • This will probably answer your question. https://stackoverflow.com/a/55741612/2809221 – ejwill Dec 29 '20 at 21:31

1 Answers1

1

Get the raw body using ReadAsStringAsync, then use Convert.FromBase64String() to convert it to bytes.

string base64 = await request.Content.ReadAsStringAsync();
byte[] bytes = Convert.FromBase64String(base64);
System.IO.File.WriteAllBytes("test.pdf", bytes);
John Wu
  • 50,556
  • 8
  • 44
  • 80