Skip to content

Instantly share code, notes, and snippets.

@kuon
Created January 29, 2017 13:54
Show Gist options
  • Save kuon/561376a19fcf498f1481b1e87877d64d to your computer and use it in GitHub Desktop.
Save kuon/561376a19fcf498f1481b1e87877d64d to your computer and use it in GitHub Desktop.
Java to javascript file upload
export function readFile() {
let path = Android.imagePath();
let base64 = Android.imageData();
// If there is an escaped / in the name, this will produce wrong result
// but still give proper type
let filename = path.split('/').pop();
let type = getType(filename);
let byteString = atob(base64);
let intArray = new Uint8Array(byteString.length);
for (let i = 0; i < byteString.length; i += 1) {
intArray[i] = byteString.charCodeAt(i);
}
let f = {
_buffer: intArray.buffer,
size: byteString.length,
name: filename,
type
};
// Here you can use f the way you want.
// xhr.send(f._buffer) will work
}
// This is very limited, but enough for my use.
// You might want to add another Java interface to use Android native
// type detection (if such thing exists)
function getType(path: string) {
if (path.match(/\.png$/)) {
return "image/png";
} else if (path.match(/\.jpg$/)) {
return "image/jpeg";
} else if (path.match(/\.pdf$/)) {
return "application/pdf";
} else {
return "application/octet-stream";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment