Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
HTML5 File API readAsBinaryString reads files as much larger and different than files on disk
When using HTML5 File API's readAsBinaryString() method, the resulting binary string can appear much larger than the original file due to character encoding issues and inefficient string representation of binary data.
The Problem with readAsBinaryString
The readAsBinaryString() method converts binary data to a string format, which can cause size inflation and encoding problems. This is especially problematic when manually creating multipart/form-data requests.
Recommended Solution: Use FormData with File Objects
Instead of reading files as binary strings, use FormData with the original File objects. This preserves the file's binary integrity and size.
<!DOCTYPE html>
<html>
<head>
<title>File Upload Example</title>
</head>
<body>
<input type="file" id="fileInput" multiple>
<button onclick="uploadFiles()">Upload Files</button>
<script>
function uploadFiles() {
const fileInput = document.getElementById('fileInput');
const files = fileInput.files;
if (files.length === 0) {
alert('Please select files to upload');
return;
}
display('/upload', files);
}
function display(url, files) {
var myForm = new FormData();
// Append each file directly to FormData
for (var j = 0, file; file = files[j]; ++j) {
myForm.append('file_' + j, file);
console.log('File:', file.name, 'Size:', file.size, 'bytes');
}
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function(e) {
if (xhr.status === 200) {
console.log('Upload successful');
} else {
console.log('Upload failed');
}
};
xhr.onerror = function() {
console.log('Upload error occurred');
};
// Send the FormData directly
xhr.send(myForm);
}
</script>
</body>
</html>
Why This Approach Works Better
Using FormData with File objects avoids the problems of readAsBinaryString():
- No size inflation: Files maintain their original size
- Proper encoding: Binary data is handled correctly
- Automatic headers: Content-Type is set automatically
- Browser optimization: Native handling is more efficient
Comparison: File Size Handling
| Method | Size Accuracy | Encoding Issues | Performance |
|---|---|---|---|
readAsBinaryString() |
Often inflated | Yes | Poor |
FormData + File |
Exact | No | Optimal |
Key Points
- Avoid
readAsBinaryString()for file uploads - Use
FormDatawith originalFileobjects - Let the browser handle binary data encoding
- Monitor upload progress using
xhr.upload.onprogressevent
Conclusion
Using FormData with File objects instead of readAsBinaryString() prevents file size inflation and encoding issues. This approach maintains file integrity and provides better upload performance.
