Convert a file from to Base64 using JavaScript and

2020-04-17 15:14发布

问题:

I am trying to convert pdf and image files to base 64 using javascript and convert it back to file using C# in WEB API.

Javascript

var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
    var fileToLoad = filesSelected[0];
    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent) 
    {
        var textAreaFileContents = document.getElementById("textAreaFileContents");
        textAreaFileContents.innerHTML = fileLoadedEvent.target.result;
    };
    fileReader.readAsDataURL(fileToLoad);
}

C#

Byte[] bytes = Convert.FromBase64String(dd[0].Image_base64Url);
File.WriteAllBytes(actualSavePath,bytes);

But in API I'm getting exception as {"The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. "}

Please tell me how to proceed with this... Thanks

回答1:

According to MDN: FileReader.readAsDataURL those generated URLs are prefixed with something like data:image/jpeg;base64,. Have a look at your generated string. Look for the occurence of base64, and take the base64 data that starts after this prefix.



回答2:

Because the FileReader.readAsDataURL() produces a string that is prefixed with extra metadata (the "URL" portion), you need to strip it off on the C# side. Here's some sample code:

// Sample string from FileReader.readAsDataURL()
var base64 = "data:image/jpeg;base64,ba9867b6a86ba86b6a6ab6abaa====";

// Some known piece of information that will be in the above string
const string identifier = ";base64,";

// Find where it exists in the input string
var dataIndex = base64.IndexOf(identifier);

// Take the portion after this identifier; that's the real base-64 portion
var cleaned = base64.Substring(dataIndex + identifier.Length);

// Get the bytes
var bytes = Convert.FromBase64String(cleaned);

You could condense this down if it's too verbose, I just wanted to explain it step by step.

var bytes = Convert.FromBase64String(base64.Substring(base64.IndexOf(";base64,") + 8));