Reputation: 1000
I am using react-dropzone
to handle file upload on my website. When successfully loading a file, the dropzone triggers the following callback:
onDrop: function (acceptedFiles, rejectedFiles) {
myFile = acceptedFiles[0];
console.log('Accepted files: ', myFile);
}
I would like to base64 encode this file. When doing :
var base64data = Base64.encode(myFile)
console.log("base64 data: ", base64data) // => base64 data: W29iamVjdCBGaWxlXQ==W29iamVjdCBGaWxlXQ==
Regardless of file uploaded, it always prints out the same string.
Am I missing something ? I need to base64 encode this file (always images)
Upvotes: 1
Views: 10739
Reputation: 329
Base on your code I will recommend using the helper functions atob() to decode and btoa() to encode to base64 for more details click here Example
let base64data = btoa(stringToEncode)
Below is a sample of what you requested using FileReader() instead (this is something I have worked on).
To get the content of the file reader in react I used the callback function to update the state as used in the MDN Web docs.
// state to store the base64 data
const [base64File, setbase64File] = useState(null);
// Create the callback function
const base64Callback = async (err, res) => {
if (!err) {
setbase64File(res); // setting the state is the important part
} else {
setbase64File(null);
}
};
// call function to convert to base64
onDrop: function (acceptedFiles, rejectedFiles) {
myFile = acceptedFiles[0];
getBase64(myFile, base64Callback);
console.log('Accepted files: ', myFile);
}
async function getBase64(file, callback) {
const reader = new FileReader();
reader.onload = () => callback(null, reader.result);
reader.onerror = (error) => callback(error);
reader.readAsDataURL(file);
}
export default getBase64;
The above code is a modified version of code from the MDN Web docs site click for more
Upvotes: 0
Reputation: 569
If you want it in a neat method that works with async / await, you can do it this way
const getBase64 = async (file: Blob): Promise<string | undefined> => {
var reader = new FileReader();
reader.readAsDataURL(file as Blob);
return new Promise((reslove, reject) => {
reader.onload = () => reslove(reader.result as any);
reader.onerror = (error) => reject(error);
})
}
Upvotes: 0
Reputation: 2691
This JS Bin is a working example of converting a File to base64: http://jsbin.com/piqiqecuxo/1/edit?js,console,output . The main addition seems to be reading the file using a FileReader
, where FileReader.readAsDataURL()
returns a base64 encoded string
document.getElementById('button').addEventListener('click', function() {
var files = document.getElementById('file').files;
if (files.length > 0) {
getBase64(files[0]);
}
});
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
Upvotes: 10