I'm getting JAVA.io.IOException received server error. below is the code to upload file to amazon s3 from phonegap app.
I'm following example from this link:
http://coenraets.org/blog/2013/09/how-to-upload-pictures-from-a-phonegap-app-to-amazon-s3/
var s3Uploader = (function () {
var s3URI = encodeURI("http://***********.s3-website-us-west-2.amazonaws.com/");
policyBase64 = "base64 string removed";
signature = "base64 string removed";
awsKey = 'AWSAccessKeyId removed';
acl = "public-read";
function upload(imageURI, fileName) {
var deferred = $.Deferred()
var ft = new FileTransfer();
options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileName;
options.mimeType = "image/jpeg";
options.chunkedMode = true;
options.params = {
"key": fileName,
"AWSAccessKeyId": awsKey,
"acl": acl,
"policy": policyBase64,
"signature": signature,
"Content-Type": "image/jpeg"
};
ft.upload(imageURI, s3URI,
function (e) {
console.log(e);
deferred.resolve(e);
},
function (e) {
console.log(JSON.stringify(e));
deferred.reject(e);
}, options);
return deferred.promise();
}
return {
upload: upload
}
}());
var $img = $('img', '.scroller');
takePicture = function (e) {
var options = {
quality: 45,
targetWidth: 1000,
targetHeight: 1000,
destinationType: Camera.DestinationType.FILE_URI,
encodingType: Camera.EncodingType.JPEG,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
};
navigator.camera.getPicture(
function (imageURI) {
alert(imageURI);
alert(imageURI);
$img.attr('src', imageURI);
var fileName = "" + (new Date()).getTime() + ".jpg";
s3Uploader.upload(imageURI, fileName)
.done(function () {
alert("S3 upload succeeded");
})
.fail(function () {
alert("S3 upload failed");
});
},
function (message) {
alert(JSON.stringify(message));
}, options);
return false;
};
$('.camera-btn').on('click', takePicture);
Related
I am Developing an Ionic Application that Upload, downloads, and delete attachments
Here I use the File Plugin inside the platform. ready() and build APK. when I run the APK on an android device the code inside the Platform.ready is not getting fired what is the problem???
import { Platform } from '#ionic/angular';
import { File } from '#ionic-native/file/ngx';
constructor(private cFile: File,private platform: Platform){}
DownloadAttachment()
{
var buffer = pFilebytearray.replace(/\"/g, "");
var byteCharacters = atob(buffer);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
this.cFile.dataDirectory
var byteArray = new Uint8Array(byteNumbers);
let aType: any = "";
let aMimeTypeJson = {} as any;
aMimeTypeJson = this.GetMimeType(pAttachmentType.toLowerCase())
aType = aMimeTypeJson.MimeType;
var blob1 = new Blob([byteArray], { type: aType });
alert("completed the Name Seperation and Blob Creation")
this.platform.ready().then(() => {
alert("Download Starts...");
let result = this.cFile.createDir(this.cFile.externalDataDirectory, "Documents", true).then(data => {
let dirpath = data.toURL();
alert("Dir created at" + dirpath);
this.cFile.writeFile(dirpath, pAttachmentName, blob1, { replace: true })
.then((Result) => {
this.MessageDialog("Message", "Attachment downloaded " + dirpath, false, true);
}, (error) => {
this.MessageDialog("Message", "Attachment not downloaded", false, true);
});
}).catch(error => {
alert("error" + error);
});
})
}
The Error Solved for me after using Async, await. This makes the code wait till the platform gets ready
async AttachmentDownload(pFilebytearray, pAttachmentType, pAttachmentName): Promise<void> {
alert("entering AttachmentDownload")
var buffer = pFilebytearray.replace(/\"/g, "");
var byteCharacters = atob(buffer);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
this.cFile.dataDirectory
var byteArray = new Uint8Array(byteNumbers);
let aType: any = "";
let aMimeTypeJson = {} as any;
aMimeTypeJson = this.GetMimeType(pAttachmentType.toLowerCase())
aType = aMimeTypeJson.MimeType;
var blob1 = new Blob([byteArray], { type: aType });
alert("completed the Name Seperation and Blob Creation")
await this.platform.ready().then(() => {
alert("Download Starts...");
let result = this.cFile.createDir(this.cFile.externalDataDirectory, "Documents", true).then(data => {
let dirpath = data.toURL();
alert("Dir created at" + dirpath);
this.cFile.writeFile(dirpath, pAttachmentName, blob1, { replace: true })
.then((Result) => {
this.MessageDialog("Message", "Attachment downloaded " + dirpath, false, true);
}, (error) => {
this.MessageDialog("Message", "Attachment not downloaded", false, true);
});
}).catch(error => {
alert("error" + error);
});
})
}
I am using this script in order to save a .pdf file in local with cordova on Android
I have this code that works perfecly on android8 but I does not work on android10, I am not facing an error , just does not work
var descargarPDF = (urlDescarga, tipoDocumento) => {
sessionStorage.platform = 'android';
var fileTransfer = new FileTransfer();
if (tipoDocumento == 1) {
filename = "example1.pdf"
}
if (tipoDocumento == 2) {
filename = "example2.pdf"
}
try {
if (sessionStorage.platform.toLowerCase() == "android") {
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, onFileSystemSuccess, onError);
}
else {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onError);
}
}
catch (err) {
alert("ER - " + err.message);
}
function onError(e) {
alert("onError");
};
function onFileSystemSuccess(fileSystem) {
var entry = "";
if (sessionStorage.platform.toLowerCase() == "android") {
entry = fileSystem;
}
else {
entry = fileSystem.root;
}
entry.getDirectory("Cordava", { create: true, exclusive: false }, onGetDirectorySuccess, onGetDirectoryFail);
};
function onGetDirectorySuccess(dir) {
dir.getDirectory("Data", { create: true, exclusive: false }, onGetDirectorySuccess1, onGetDirectoryFail);
};
function onGetDirectorySuccess1(dir) {
cdr = dir;
dir.getFile(filename, { create: true, exclusive: false }, gotFileEntry, errorHandler);
};
function gotFileEntry(fileEntry) {
var uri = encodeURI(urlDescarga);
fileTransfer.download(uri, cdr.nativeURL + filename,
function (entry) {
openFile();
},
function (error) {
endLoader();
alert(" error " + error.source);
},
true);
};
//This method is call just on Android10
function onGetDirectoryFail(error) {
alert("onGetDirectoryFail");
};
What I doing wrong?
Using android, browsers (FF, Chrome, ...) crash when i use this instruction :
img.src = blob;
Any idea ?
the complete source :
$("#file-input").on("change", function (e) {
if (window.URL) {
var img = document.createElement("img");
img.onload = function (e) {
img.width = 100;
document.getElementById("preview").appendChild(img);
URL.revokeObjectURL(img.src);
parent.window.$.mobile.loading("show");
window.setTimeout(function () {
startUploading();
}, 2500);
};
var blob = URL.createObjectURL(e.target.files[0]);
img.src = blob;
}
else {
// fallback to FileReader for FF3.6
reader = new FileReader();
reader.onload = (function (theFile) {
return function (e) {
document.getElementById('preview').innerHTML = ['<img src="', e.target.result, '" width="100" />'].join('');
parent.window.$.mobile.loading("show");
window.setTimeout(function () {
startUploading();
}, 2500);
};
})(f);
reader.readAsDataURL(e.target.files[0]);
}
});
thanks in advance.
I am new to phonegap and i am having the issue when uploading the image from android device, the I think the window.resolveLocalFileSystemURI function throws an Error calling method on NPObject error, my complete code is as below. Please have a look and share your ideas.
navigator.camera.getPicture(function (imageURI) {
var _this = this;
var encodedURL = encodeURI("http://api.xyz.com/DataService/DataService.svc/UploadImage");
try {
this.op = new FileUploadOptions();
this.op.fileKey = "file";
this.op.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
this.op.mimeType = "image/jpeg";
this.op.chunkedMode = false;
this.op.headers = { Connection: "close" };
this.ft = new FileTransfer();
if (window.device != undefined && device.platform == "Android") {
window.resolveLocalFileSystemURI(imageURI, function (fileEntry) {
fileEntry.file(function (fileObj) {
var fileFullPath = fileObj.fullPath;
_this.op.fileName = fileFullPath.substr(fileFullPath.lastIndexOf('/') + 1);
_this.ft.upload(fileFullPath, encodedURL, function (data) { alert("Success: " + JSON.stringify(data)); }, function (data) { alert("Failour: " + JSON.stringify(data)); }, _this.op, true);
});
});
} else {
this.ft.upload(imageURI, encodedURL, function (data) { alert("Success: " + JSON.stringify(data)); }, function (data) { alert("Failour: " + JSON.stringify(data)); }, this.op, true);
}
} catch (_error) {
alert(_error);
}
},
function (message) { },
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
});
}
I have this code for uploading photo on server
photo: function () {
var self = this;
navigator.camera.getPicture(function
getPhotoTicket(function (ticket) {
var options = new FileUploadOptions();
var fileName = {};
options.fileKey = "upload_file";
try {
window.resolveLocalFileSystemURI(imageURI, onSuccess, onError);
} catch (e) {
console.log(e.toString());
fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1)+'.jpg';
}
options.fileName = fileName;
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.headers = {
Connection: "keep-alive"
};
options.httpMethod = "POST";
var params = {};
params.upload_ticket = ticket;
options.params = params;
function reload() {
getProfile(userID, function () {
app.profile_editor();
}, true);
}
function onSuccess(fileEntry) {
fileName = fileEntry.name;
}
function onError(fileEntry) {
fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1) + '.jpg';
}
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI(URL + "api/index/fileupload"), function (success) {
alert('PHOTO UPDATED');
reload();
}, function (error) {
alert('error');
}, options);
});
}, function () {
console.log("error getting image")
}, {
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: navigator.camera.DestinationType.FILE_URI
});
}
it works fine on Android 4.3 and lower. But on Android KitKat i get imageURI like:
content://com.android.providers.media.documents/document/image%3A352
In this post Unable to load image when selected from the gallery on Android 4.4 (KitKat) using PhoneGap Camera Plugin
MBillau suggest to set the destination type to DATA_URL. I tried but had no success. Could someone suggest how I need to refactor my code?