Phonegap - Image URL wrong from camera when sending through filetransfer? - javascript

So It appears that I have stumbled across a very bizarre issue with phonegap 2.2.0.
I am trying to take a picture, and send it through the filetransfer plugin, like so:
if(navigator.camera) {
navigator.camera.getPicture(function(imageURI){
console.log('captured image = '+imageURI);
$('#photoConfirmation .image-preview').attr('src', imageURI);
self.photoURI = imageURI;
$('#photoConfirmation').show().simpledialog2({
'mode' : 'bool',
'prompt' : '',
'useModal': true,
'zindex':1001,
'callbackClose': function(e){
$('#photoConfirmation').hide();
}
});
},
function(message){
alert('Failed to get picture: ' + message);
}, {
sourceType:1,
quality: 50,
destinationType:1
});
} else {
alert('Camera is not supported on this device.');
}
var options = new FileUploadOptions();
options.fileKey="files[]";
options.fileName = 'image_something'.jpg';
options.mimeType="image/jpeg";
options.chunkedMode = false;
var params = new Object();
params.extraData= 'object-' + anObject.id;
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, "http://someupload.com/destination/url", function(r){alert('Finished upload!');}, function(error){console.log(error);alert('Error uploading image with code: ' +error.code)}, options);
The problem is, this shows up in the preview, but does not upload! The picture is definitely getting captured because I see it in the image preview... I could've sworn I did something like this before. Does anyone see anything that I am doing wrong here?

There is a reference implementation of the FileTransfer plugin (which uses the captured photo from a camera) on the Cordova API Documentation, which many differences in it's implementation from yours. Reading though your code it looks like you are firing off a File Transfer before you capture the photo (and create the imageURI). Also you are using numerical constants for sourceType and destinationType. Though these are most likly not causing the problem you are experiencing, the correct forms for these is:
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
Here is an example with some small typo fixes (I'm assuming that extra ' in the fileName isn't a part of your code) of what should be a working version:
if (navigator.camera) {
navigator.camera.getPicture(
function (imageURI) {
console.log('captured image = ' + imageURI);
$('#photoConfirmation .image-preview').attr('src', imageURI);
self.photoURI = imageURI;
$('#photoConfirmation').show().simpledialog2({
'mode': 'bool',
'prompt': '',
'useModal': true,
'zindex': 1001,
'callbackClose': function (e) {
$('#photoConfirmation').hide();
var options = new FileUploadOptions();
options.fileKey = "files[]";
options.fileName = 'image_something.jpg';
options.mimeType = "image/jpeg";
options.chunkedMode = false;
var params = new Object();
params.extraData = 'object - ' + anObject.id;
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, "http://someupload.com/destination/url", function (r) {
alert('Finished upload!');
}, function (error) {
console.log(error);
alert('Error uploading image with code: ' + error.code)
}, options);
}
});
},
function (message) {
alert('Failed to get picture: ' + message);
}, {
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI
});
} else {
alert('Camera is not supported on this device.');
}

Related

AngularJS variable is not reflecting instantly on View but Updated on Controller

What I am trying to do is updating AngularJS variable from controller function and when I console its updated instantly but when I print it on View it updates after about 5-8 secs.
I try with both ng-model and curly braces but in both cases it after few seconds in view but in console its updated instantly.
I call uploadedMedia function in fine uploader callback and its working fine with console.log
$scope.UploadedMedia = function(){
console.log($scope.Album[0].Media.length);
$scope.UploadedMediaVal = $scope.Album[0].Media.length;
console.log($scope.Album[0].Media.length);
}
$scope.initFineUploader = function(){
var fcnt = 0;
var iuploader = new qq.FineUploaderBasic({
multiple: true,
autoUpload: true,
title: "Attach Photos",
button: $("li[data-type='uploadMediabutton']")[0],
request: {
endpoint: site_url + "api/uploadimage",
customHeaders: {
"Accept-Language": accept_language
},
params: {
Type: 'ratings',
unique_id: function() {
return '';
},
LoginSessionKey:LoginSessionKey,
DeviceType:'Native'
}
},
maxConnections : 50,
validation: {
acceptFiles: '.bmp,.jpeg,.jpg,.gif,.png',
allowedExtensions: ['bmp','jpeg', 'jpg', 'gif', 'png', 'JPEG', 'JPG', 'GIF', 'PNG'],
sizeLimit: 4194304 // 40mb
},
callbacks: {
onUpload: function(id, fileName) {
$scope.Album[0].Media.push({MediaGUID:'',ImageName:'',Caption:'',MediaType:'Image',VideoLength:'',ConversionStatus:'',IsLoader:'1',FileName:fileName});
$scope.UploadedMedia();
$('.rating-submit').attr('disabled','disabled');
fcnt++;
},
onProgress: function(id, fileName, loaded, total) {
$scope.Uploading = 1;
},
onComplete: function(id, fileName, responseJSON) {
fcnt--;
if (responseJSON.Message == 'Success') {
$($scope.Album[0].Media).each(function(mk,mv){
if(mv.FileName == fileName){
$scope.Album[0].Media[mk]['MediaGUID'] = responseJSON.Data.MediaGUID;
$scope.Album[0].Media[mk]['ImageName'] = responseJSON.Data.ImageName;
$scope.Album[0].Media[mk]['IsLoader'] = 0;
}
});
var fNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
$('li[data-filename="'+fileName+'"]').remove();
setTimeout(function(){
$('li[data-filename="'+fileName+'"] .m-laoder').remove();
},1000);
} else {
$('li[data-filename="'+fileName+'"]').remove();
}
if(fcnt <= 0){
$scope.Uploading = 0;
$('.rating-submit').removeAttr('disabled');
$('.attached-media-list li.media-loader').remove();
}
$scope.UploadedMedia();
},
onValidate: function(b) {
if($scope.Album[0].Media.length>=10){
showResponseMessage('You can upload maximum 10 images, please delete any old image to upload new one.','alert-danger');
return false;
}
var validExtensions = ['bmp','jpeg', 'jpg', 'gif', 'png', 'JPEG', 'JPG', 'GIF', 'PNG']; //array of valid extensions
var fileName = b.name;
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
if ($.inArray(fileNameExt, validExtensions) == -1) {
showResponseMessage('Allowed file types only bmp, jpeg, jpg, gif and png.','alert-danger');
return false;
}
if (b.size > 4194304) {
showResponseMessage('Image file should be less than 4 MB','alert-danger');
}
},
onError: function(){
$('.attached-media-list li.media-loader:last-of-type').remove();
}
}
});
}
<div>
{{UploadedMediaVal}}
<span ng-bind="UploadedMediaVal"></span>
</div>
Write $scope.$apply();, after modifying your variable.
How do you invoke SomeOtherFunction? Is it triggered in the angular digest phase or by a dom event. In the second case you have to wrap the commands with a $scope. $apply (){}
Here is sample demo you code that may help you http://dojo.telerik.com/UmIvO
But I think is it possible to share you album array to test
I have tested it is giving immediate response could you please check with your album array. So that may help you out.

How do i force download Video in AngularJs from Amazon S3?

I have written code to download a video uploaded to amazon s3 using aws javascript sdk. Everything works fine but for some videos open up in the browser and start playing. Here is the code below:
View:
Download Video
Controller:
$scope.downloadVideo = function (video) {
videoLocation = video.video_location;
var bucketPath = videoLocation.substring(0, videoLocation.lastIndexOf("/") + 1);
bucketPath = bucketPath.substring(0, bucketPath.length - 1);
var fileName = videoLocation.substring(videoLocation.lastIndexOf("/") + 1, videoLocation.length);
var videoSignedUrl = VideoFactory.downloadVideo(bucketPath,fileName);
$window.open(videoSignedUrl);
}
VideoFactory :
downloadVideo: function (bucketPath,fileName) {
bucketName = aws.bucket_name;
options = {
accessKeyId : 'XXXXXXXXXXXXXXXXXXXXX',
secretAccessKey : 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
region : 'XXXXXX'
}
var params = {
Bucket: bucketName + '/'+ bucketPath, Key: fileName, Expires: 60
};
var s3 = new AWS.S3(options);
var url = s3.getSignedUrl('getObject', params);
return url;
}
So when videos open up in a new window they start getting downloaded at the bottom of the browsers. But for some unknown videos they open up in a window and start playing. How can i stop this in angularjs. What is the suggested workaround and how do others handle this kind of issues??
I did google but most of the stackoverflow answers here say to open files in window and browsers automatically downloads it.
Try this solution it may help you.enter link description here
View:
Download Video
<a id="ExportToExcel" style="display: none;"></a>
Controller:
$scope.downloadVideo = function (video) {
videoLocation = video.video_location;
var bucketPath = videoLocation.substring(0, videoLocation.lastIndexOf("/") + 1);
bucketPath = bucketPath.substring(0, bucketPath.length - 1);
var fileName = videoLocation.substring(videoLocation.lastIndexOf("/") + 1, videoLocation.length);
var videoSignedUrl = VideoFactory.downloadVideo(bucketPath,fileName);
document.getElementById("ExportToExcel").href = videoSignedUrl;
document.getElementById("ExportToExcel").click();
}
The trick that worked was making the video as an attachment during the video upload to S3 :
options = {
accessKeyId : 'xxxxxxxxxxxxxxxxxxxxxxx',
secretAccessKey : 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
region : 'xxxxxx'
}
var s3 = new AWS.S3(options);
var params = {
Bucket : bucketName + '/' + bucketStructure,
Key: fileName,
ContentType: file.type,
Body: file,
ServerSideEncryption: 'AES256',
ACL : 'private',
ContentDisposition: 'attachment; filename=' + fileName,
ContentType: 'application/octet-stream'
};
s3.putObject(params, function(err, data) {
if(err) {
// There Was An Error With Your S3 Config
console.log('AWS Error : '+err.message);
return false;
}
else {
console.log('AWS Video upload done!');
}
})
This would make the video to force download automatically when a signed url was used. Has worked for most of the video mime types for me.

Phonegap - Blackberry filetransfer with headers 401 error

This should be a simple solution, but it's driving me crazy.
I am using the FileTransfer plugin to upload a photo taken with the camera to the server, pretty much exactly like the docs. I am using basic HTTP authentication, which works perfectly on Android and iOS, but on blackberry, it's returning a 401 - Unauthorized error. Do you have to do something special to get the file upload working on the BB?
I have the whitelist set to *, so that shouldn't be the issue, plus it's working on all the other devices...
module.uploadPhoto = function(imageURI, obj) {
$.mobile.loading( 'show', {
text:'Sending File...',
textVisible:true
});
var uploadURL = CONTEXT+'api/'+obj.id+"/files";
var options = new FileUploadOptions();
options.fileKey="files[]";
options.fileName = 'image_' + imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
var params = new Object();
params.thread = 'object-' + obj.id;
options.params = params;
options.headers = {
Authorization: 'Basic ' + loginCreds
};
var ft = new FileTransfer();
ft.upload(imageURI, uploadURL,
function(r){
custAlert('Finished upload!', 'Photo upload successful.');
$.mobile.loading( 'hide' );
},
function(error){
custAlert('Error uploading image with object: ' +error.http_status+ ' and code - ' +error.code, 'Error Uploading');
$.mobile.loading( 'hide' );
},
options, true);
}
Does anyone know what's going on here? I am going a bit crazy... Thanks.

Phonegap - iOS filetransfer not working with authorization header

I am trying to upload an image captured from the camera to a server. The method below works great for any Android devices, but for some reason, it's failing on iOS. It's returning a 401 error, which doesn't make sense:
var options = new FileUploadOptions();
options.fileKey="files[]";
options.fileName = 'image_' + obj.id + '.jpg';
options.mimeType="image/jpeg";
options.chunkedMode = false;
var params = new Object();
params.headers = {
Authorization: 'Basic ' + loginCreds
}
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, CONTEXT+'URL/files",
function(r){
alert('Finished upload!');
$.mobile.loading( 'hide' );
},
function(error){
console.log(error.http_status);
alert('Error uploading image: ' +error.http_status+ ' and code - ' +error.code);
$.mobile.loading( 'hide' );
},
options, true);
I know there was an issue setting headers in iOS, but I thought that was fixed as of Phonegap 1.9.0. Am I doing something wrong here?
I checked the server logs, and it seems like the authorization header is just simply not being set in iOS. Strange...
So figured this one out after a whole day of wrestling with it. So it turns out, Android and iOS differ on how they can take the headers parameter.
Android:
var params = new Object();
params.headers = {Authorization: 'Basic ' + loginCreds};
options.params = params;
OR
options.headers = {Authorization: 'Basic ' + loginCreds};
iOS:
options.headers = {Authorization: 'Basic ' + loginCreds};
Hope this saves someone somewhere some headaches...

upload images or videos to remote server using phonegap

I am doing project in android phonegap.Here I want to upload images and videos to remote server.
I used the following link.
http://zacvineyard.com/blog/2011/03/upload-a-file-to-a-remote-server-with-phonegap
I also change some options like options.chunkedMode = false ,android:debuggable="true" and
. But still it shows error code 3.I am using the cordova-2.0.0.js version.Can anyone suggest some answer.
My js code is
**
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
// Do cool things here...
}
function getImage() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
},
{quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "url of ther server/upload.php", win, fail, options, true);
console.log("H");
}
function win(r) {
console.log("HIIIIIiiii");
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("There is something");
alert("An error has occurred: Code = " + error.code);
}
</script>
**
and my php code is
<?php
print_r($_FILES);
$new_image_name = "namethisimage.jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$new_image_name);
?>
Thanks.
Have you added the URL in question to your whitelist?
e.g. in config.xml do you have something like:
<access origin="www.myurl.com" subdomains="true" />
or
<access origin="*" />
which allows all URLs.
Error code 3 is a FileTransferError.CONNECTION_ERR by the way.

Categories

Resources