Browsers crash when using URL.createObjectURL - android

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.

Related

platform.ready() method is not firing in Android device using ionic

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);
});
})
}

Unable to retrieve access token for Moodle on Android phone

I have created an authentication service based on Jason Watmore's example, and it works fine in the Ripple emulator for Android, logs in, saves the token to jStorage, and uses it to access other web services.
It was also working in the actual Android phone till yesterday.
I have tested to see if jStorage is working in my Android phone (it is), and I have tried removing all the app's data using the Settings.
Any idea why the Android phone is not fetching the token from the Moodle server (but the emulator is fetching it)?
Here's my service:
myApp.factory('AuthenticationService',
['$http', '$cookies', '$rootScope', '$timeout', '$log',
function ($http, $cookies, $rootScope, $timeout, $log) {
var service = {};
service.Login = function (username, password, callback) {
//$log.info('Login function called');
if ((username.length && password.length) && (username !== '' && password != '')) {
var loginUrl = 'https://my.moodle.url/local/token.php';
// use $.param jQuery function to serialize data from JSON
var data = $.param({
username: username,
password: password,
service: 'brookesid_ws'
});
//$log.info(data);
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post(loginUrl, data, config)
.success(function (data, status, headers, config) {
$log.info(data);
myToken = data.token;
dataString = JSON.stringify(data);
if (dataString.indexOf('error') > 0) {
$rootScope.className = 'error';
$rootScope.PostDataResponse = 'Invalid user credentials, please try again';
$rootScope.isAuthenticated = false;
$rootScope.dataLoading = false;
}
else {
$.jStorage.set('session', myToken, { TTL: 28800000 });
//$cookies.put('session', myToken);
}
$rootScope.isAuthenticated = true;
// $log.info('isAuthenticated = true');
callback(dataString);
})
.error(function (data, status, header, config) {
$rootScope.isAuthenticated = false;
$rootScope.ResponseDetails = "data: " + data +
"<br />status: " + status +
"<br />headers: " + header +
"<br />config: " + config;
responsedata = JSON.stringify(data);
callback(responsedata);
$log.info('error: '+responsedata);
});
} else {
$rootScope.className = 'error';
$rootScope.isAuthenticated = false;
$rootScope.PostDataResponse = 'Please enter a username and password';
}
};
service.SetCredentials = function (sessionToken) {
var JSONObject = JSON.parse(sessionToken);
var key = 'token';
myToken = JSONObject[key];
$log.info('session Token: ' + sessionToken);
$log.info('myToken: ' + myToken);
$rootScope.globals = {
currentUser: {
token: myToken
}
};
$http.defaults.headers.common['Authorization'] = 'Basic ' + sessionToken; // jshint ignore:line
//retrieve last login date and then update it
$rootScope.lastLogin = $.jStorage.get('lastLogin', '');
var today = new Date();
epochToday = Math.round(today.getTime() / 1000);
$.jStorage.set('lastLogin', epochToday, { TTL: 28800000 });
//$log.info('Rootscope Last Login: '+$rootScope.lastLogin);
$.jStorage.set('globals', $rootScope.globals, { TTL: 28800000 });
$.jStorage.set('session', myToken, { TTL: 28800000 });
$.jStorage.set('loginStatus', 'logged in', { TTL: 28800000 });
$log.info('Token (jStorage) ' + $.jStorage.get('session', ''));
//$log.info('Last login (jStorage) ' + $.jStorage.get('lastLogin', ''));
//$log.info('Login status (jStorage) ' + $.jStorage.get('loginStatus', ''));
};
service.ClearCredentials = function () {
$rootScope.globals = {};
//$cookies.remove('globals');
//$cookies.remove('session');
$.jStorage.deleteKey('globals');
$.jStorage.deleteKey('session');
$http.defaults.headers.common.Authorization = 'Basic ';
};
return service;
}])
Here is my login Controller:
.controller('loginCtrl',
['$scope', '$rootScope', '$location', 'AuthenticationService', '$routeParams', '$http',
function ($scope, $rootScope, $location, AuthenticationService, $routeParams, $http) {
$scope.login = function () {
$scope.dataLoading = true;
AuthenticationService.Login($scope.username, $scope.password, function (response) {
responsedata = JSON.stringify(response);
/* error handling*/
if (responsedata.indexOf('error') > 0 || responsedata.indexOf('invalid') > 0) {
$scope.error = response.message;
$rootScope.className = 'error';
$rootScope.dataLoading = false;
} else {
AuthenticationService.SetCredentials(response);
console.log('response: '+response);
$location.path('/home');
};
});
};
$scope.logout = function () {
$rootScope.dataLoading = false;
$rootScope.hideMe = true;
$rootScope.PostDataResponse = '';
$rootScope.ResponseDetails = '';
//alert('logging out');
AuthenticationService.ClearCredentials();
};
$scope.showMenuPanel = function () {
$scope.hideMenuPanel = false;
};
$scope.doHideMenuPanel = function () {
$scope.hideMenuPanel = true;
$rootScope.PostDataResponse = '';
};
}])
It was actually the Cordova app's URL whitelisting settings that were causing the problem.

Phonegap "Error calling method on NPObject" while uploading the image from android device

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
});
}

File upload issues phonegap app to Amazon s3

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);

Can't upload photo from Storage Access Framework on Android 4.4 using phonegap

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?

Categories

Resources