how to convert a PDF to a base64string in .net

655 views Asked by At

trying to convert a pdf object a user uploads via form to a base64string

public async Task<IActionResult> AddDocument([Bind("formFile")]File file)
{
     byte[] a = System.IO.File.ReadAllBytes(file);
    
     string s = Convert.ToBase64String(a);
   
    ...    
}

my file input is as such:

<input class="form-control" type="file" id="formFile" style="display:block" name="formFile">

however i am getting this error message:

cannot convert from System.IO.FileInfo to string

is it not possible to convert a pdf to a base64string?

1

There are 1 answers

0
Mario Vernari On

According to what I made in my project, I'd do the following:

public async Task<IActionResult> AddDocument(CancellationToken token)
{
     IFormCollection fcoll = await this.Request.ReadFormAsync(token);
     IFormFile ff in fcoll.Files[0];
     //IFormFile ff in fcoll.Files["formFile"]; //alternative (better) way to retrieve the file

     byte[] a;
     using (var br = new BinaryReader(ff.OpenReadStream()))
     {
         a = br.ReadBytes((int)ff.OpenReadStream().Length);
     }

     //byte[] a = System.IO.File.ReadAllBytes(file);
    
     string s = Convert.ToBase64String(a);
   
    ...    
}

In my case, I actually have several file uploads, but that's easy to manage.