I need to read a PDF from the filesystem in Android in order to send it to a server. I cannot seem to read valid data however.
I have tried readAsDataURL
as it appears to be the fastest. However the value returned (after removing the MIME type) is invalid base64.
// read the file from the filesystem
window.resolveLocalFileSystemURL(path,
function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
// test base64 is valid
var patt = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
var b64 = evt.target.result.split(",", 2)[1];
console.log("is valid base64? " + patt.test(b64)); // false!
var bytes = atob(b64); // Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
};
//reader.readAsText(file);
reader.readAsDataURL(file);
},
function (err) {
console.error(err);
});
}, function (err) {
console.error(err);
});
I have also tried readAsText
and then converted this into base64 myself, but this is incredibly slow for large PDF files and the data when translated back is not valid.
Why is the base64 from readAsDataURL
not valid? I have tried on multiple Android devices (with and without crosswalk). Using latest version of the file plugin.
It is a known and reported issue of the File plugin of Cordova.
FileReader readAsDataURL
have issues when base 64 encoding large files. The process used is the following:
The result is not a valid base64 encoded string but is instead a string composed of multiple valid base64 encoded string appended.
One workaround instead of decoding the result is to split the data in part of 256K chunk, decode each chunk individually and then you'll be able to re-encode the whole string.
Regarding the issue , it's tagged as affecting Android 4.4.2 but the problem still exists in Android 5 & 6. Regarding the resolution, it's still not assigned to anyone.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.