mamhh
mamhh

Reputation: 85

How to process incoming pdf in ASP.NET Core Web API using C#?

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=

Upvotes: 0

Views: 1615

Answers (1)

John Wu
John Wu

Reputation: 52240

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);

Upvotes: 1

Related Questions