Goal:
- In the browser, read a file from the users file system as base64 string
- These files are up to 1.5GB
Issue:
- The followig script works perfectly fine on Firefox. Regardless of the filesize.
- On Chrome, the script works fine for smaller files (I've tested files of ~ 5MB size)
- If you pick a bigger file (e.g. 400MB) the FileReader completes without an error or exception, but returns an empty string instead of the base64 string
Questions:
- Is this a chrome bug?
- Why is there neither an error nor an exception?
- How can I fix or work around this issue?
Important:
Please note, that chunking is not an option for me, since I need to send the full base64 string via 'POST' to an API that does not support chunks.
Code:
'use strict';
var filePickerElement = document.getElementById('filepicker');
filePickerElement.onchange = (event) => {
const selectedFile = event.target.files[0];
console.log('selectedFile', selectedFile);
readFile(selectedFile);
};
function readFile(selectedFile) {
console.log('START READING FILE');
const reader = new FileReader();
reader.onload = (e) => {
const fileBase64 = reader.result.toString();
console.log('ONLOAD','base64', fileBase64);
if (fileBase64 === '') {
alert('Result string is EMPTY :(');
} else {
alert('It worked as expected :)');
}
};
reader.onprogress = (e) => {
console.log('Progress', ~~((e.loaded / e.total) * 100 ), '%');
};
reader.onerror = (err) => {
console.error('Error reading the file.', err);
};
reader.readAsDataURL(selectedFile);
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
<title>FileReader issue example</title>
</head>
<body>
<div class="container">
<h1>FileReader issue example</h1>
<div class="card">
<div class="card-header">
Select File:
</div>
<div class="card-body">
<input type="file" id="filepicker" />
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8"
crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>