Skip to content

Instantly share code, notes, and snippets.

@slothentic
Created November 10, 2019 15:41
Show Gist options
  • Save slothentic/f4f15239e6e6280b8772760fe5adfe48 to your computer and use it in GitHub Desktop.
Save slothentic/f4f15239e6e6280b8772760fe5adfe48 to your computer and use it in GitHub Desktop.
// Adapted from: https://cordova.apache.org/blog/2017/10/18/from-filetransfer-to-xhr2.html
// After scouring the internet, this is the only workable example I found
// The File object returned from resolveLocalFileSystemURL().file() is not compatible with FormData
navigator.camera.getPicture(function cameraSuccess(imageUri) {
window.resolveLocalFileSystemURL(imageUri, function(fileEntry) {
fileEntry.file(function(file) {
// imageUri - this can be used to display an image like `<img src=${imageUri} />`
// file - a "File" type, but not a normal File type that can be used with FormData
var reader = new FileReader();
reader.onloadend = function() {
// Create a blob based on the FileReader "result", which we asked to be retrieved as an ArrayBuffer
var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
var oReq = new XMLHttpRequest();
// blob can also be added to FormData
// const formData = new FormData();
// formData.append('file', blob);
oReq.open("POST", "http://mysweeturl.com/upload_handler", true);
oReq.onload = function (oEvent) {
// all done!
};
// Pass the blob in to XHR's send method
oReq.send(blob);
};
// Read the file as an ArrayBuffer
reader.readAsArrayBuffer(file);
}, function(error) {
alert("Unable to obtain picture: " + error);
});
});
}, function cameraError(error) {
alert("Unable to obtain picture: " + error);
}, options);
@slothentic
Copy link
Author

Was having a very hard time finding a solution to upload a photo using the first party Cordova camera plugin: https://github.com/apache/cordova-plugin-camera

Hopefully this can help someone who was stuck where I was trying to get this to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment