Phonegap - iOS filetransfer not working with authorization header - javascript

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...

Related

How to use vimeo-upload in node.js?

I am going to upload the video to my app of vimeo in Node/Express.
I had googling and found the package to upload the video to the vimeo, it's the vimeo-upload.
But I am not sure how to use it.
Its the format is like following.
var uploader = new VimeoUpload({
file: file,
token: accessToken,
});
uploader.upload();
I got the accesstoken in my project and think file is the binary of video.
The problem is to get the binary from video.
Please help me!
I found the issues of vimeo-upload.js as the API version of vimeo was upgraded.
The function upload() in the vimeo-upload.js, the url was changed like following.
me.prototype.upload = function() {
var xhr = new XMLHttpRequest()
xhr.open(this.httpMethod, this.url, true)
xhr.setRequestHeader('Authorization', 'Bearer ' + this.token)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onload = function(e) {
// get vimeo upload url, user (for available quote), ticket id and complete url
if (e.target.status < 400) {
var response = JSON.parse(e.target.responseText)
this.url = response.upload.upload_link
this.user = response.user
this.ticket_id = response.ticket_id
this.complete_url = defaults.api_url + response.complete_uri
this.sendFile_()
} else {
this.onUploadError_(e)
}
}.bind(this)
xhr.onerror = this.onUploadError_.bind(this)
xhr.send(JSON.stringify({
type: 'streaming',
upgrade_to_1080: this.upgrade_to_1080
}))
}

node.js download images to server from list of http requests

I'm very new at node so bear with me. I'm trying to download a series of images from an external server. So far I have been able to get it working on a limited basis. When I run the below code, only about half of the images make it though to the web page. I know that I'm not doing this correctly, and am looking for some guidance. Here is the code that I have so far
var request = require("request"),
fs = require("fs"),
views = ['sitename1', 'sitename2', 'sitename3'...]
for (var view in views) {
request({
url: 'http://' + SERVERURL + '/api/2.2/sites/' + siteID + '/workbooks/' + views[view]['workbookID'] + '/views/' + views[view]['id'] + '/previewimage',
headers: {
'Content-Type': 'image/png',
'X-Tableau-Auth': authToken
}
, encoding: 'binary'}).pipe(
fs.createWriteStream('./public/images/thumbnails/' + SITE + '/views/' + views[view]['url'] + '.png'
))
};
I want to point out that this does get some of the images saved correctly. I believe what I'm missing is a callback to make sure that the file has been successfully saved before moving on to the next item in the list. I have no idea how to implement that.
Another quick note (not important) is that I'm trying to download images from a Tableau Server using the REST api.
The face you're getting about half the images makes me wonder if you are using Tableau Online? If so, you need to ensure you're using the URI per the docs (http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_concepts_fundamentals.htm#tableau-online-uris).
Just figured it out using the async module
async.eachSeries(views, (function(view, callback) {
var thumbPath = 'public/images/thumbnails/' + req.session.SITE + '/views/' + req.session.views[view]['url'] + '.png'
request({
url: 'http://' + SERVERURL + '/api/2.2/sites/' + req.session.siteID
+ '/workbooks/' + req.session.views[view]['workbookID'] + '/views/' + req.session.views[view]['id'] + '/previewimage',
headers: {
'Content-Type': 'image/png',
'X-Tableau-Auth': req.session.authToken
}
}).pipe(
upload(thumbPath));
callback()
}),
function(err){
if(err){
console.log("a thumb failed to download")
} else {
console.log("all thumbs downloaded")
}
}
)

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 - Image URL wrong from camera when sending through filetransfer?

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

Categories

Resources