How to get the main base64 value from reader.result?

I am successful in getting the base64 value of my file but with the value am also getting the type of file and the type of string but I don’t want that. I just want the actual value as I need to send it to the backend.

Code to convert file to base64

handleUpload(e) {   var reader = new FileReader();   const file = (e.target as HTMLInputElement).files[0];   reader.readAsDataURL(file);   reader.onload = () => {     console.log(reader.result as string);   }; } 

base64

I want the value starting from ‘U’ after the ‘base64,’ word.

Add Comment
1 Answer(s)

You can simply use a RegExp for that:

reader.result.replace(/^.+?;base64,/, '') 

But as mentioned in a comment, you should also consider posting the binary as it is, without needing the conversion dance.

const file = (e.target as HTMLInputElement).files[0]; const body = new FormData; body.append('file', file); fetch('/end-point', {   method: 'POST',   body }); 

This way is both faster and more efficient, as base64 size is bigger than binary, and there’s no need to wait for the client to convert the binary file.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.