I'm trying to submit an image (either taken from camera, or selected from gallery) to my upload server by using cordova file-transfer plugin.
The camera plugin works fine, I can see the image -- taken with camera or selected from gallery -- being displayed on screen (by using <img /> tag).
When trying to implement the FileTransfer.Upload, the docs states that the upload method has some arguments, including success/error callback functions.
This is my portion of code:
function uploadPhoto() {
var imageURI = document.getElementById('ImageSource').getAttribute("src");
if (!imageURI) {
alert('Please select an image first.');
return;
}
console.log("imageURI = " + imageURI);
var url=encodeURI("http://my.server.path/upload.php");
var options = new FileUploadOptions();
options.fileKey = "file";
options.mimeType = "multipart/form-data";
options.chunkedMode = false;
console.log("Starting Transfer...");
var ft = new FileTransfer();
ft.upload(imageURI, url,
function (r) {
alert('Finished upload!');
}, function (error) {
console.log(error);
alert('Error uploading image with code: ' + error.code)
},
options
);
console.log("Finishing Transfer...");
}
The Callbacks are not firing
Running the app on an Android Emulator, I get no alert. I can't tell whether it was a success or a failure. But the strange thing is: the image file get uploaded to my server, and I can see these two lines delievered on the log:
D/CordovaLog( 2487): file:///android_asset/www/js/app.js: Line 123 : imageURI = content://media/external/images/media/24
D/CordovaLog( 2487): file:///android_asset/www/js/app.js: Line 147 : Starting Transfer...
D/CordovaLog( 2487): file:///android_asset/www/js/app.js: Line 163 : Finishing Transfer...
Can somebody kindly point me out, where should I look? Because I can't handle the response. I need to get the server response, and display a processed image back to the screen.
Related
Can anyone shed any light on why, using the Image Factory module to download and store images on Android, does it ignore the transparency on PNG graphics and give them a black background?
It works fine on iOS and everything is "as is".
Do I need to add anything to the download script to retain the transparency?
Help!
Here is my download script, I'm building using Titanium 3.5.1 GA:
function getMarker(url, filename) {
// this will enable us to have multiple file sizes per device
var filename2 = filename.replace(".png", "#2x.png");
var filename3 = filename.replace(".png", "#3x.png");
var mapMarker = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'map_marker_icons', filename);
var mapMarker2 = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'map_marker_icons', filename2);
var mapMarker3 = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'map_marker_icons', filename3);
// now we need to download the map marker and save it into our device
var getMarker = Titanium.Network.createHTTPClient({
timeout: 30000
});
getMarker.onload = function() {
// if the file loads, then write to the filesystem
if (getMarker.status == 200) {
// resize the images into non-retina, retina and retina HD and only download and resize what is actyally required
var getOriginal = ImageFactory.imageWithAlpha(this.responseData, {});
var resized2 = ImageFactory.imageAsResized(getOriginal, {
width: 50,
height: 50
});
mapMarker.write(resized2);
Ti.API.info(filename + " Image resized");
//I ALWAYS NULL ANY PROXIES CREATED SO THAT IT CAN BE RELEASED
mapMarker = null;
} else {
Ti.API.info("Image not loaded");
}
// load the tours in next
loadNav();
};
getMarker.onerror = function(e) {
Ti.API.info('XHR Error ' + e.error);
//alert('markers data error');
};
getMarker.ondatastream = function(e) {
//Ti.API.info('Download progress: ' + e.progress);
};
// open the client
getMarker.open('GET', url);
// change the loading message
MainActInd.message = 'Downloading Markers';
// show the indicator
MainActInd.show();
// send the data
getMarker.send(); }
Any help would be much appreciated!
Simon
Please try the following code, I tried it on Android and iOS with a png Url, first I GET the photo with HTTP client request, then I save it as a file with extension png and then I read it with an ImageView.
index.js:
$.win.open();
savePng("https://cdn1.iconfinder.com/data/icons/social-media-set/29/Soundcloud-128.png");
function savePng(pngUrl) {
var client = Titanium.Network.createHTTPClient({
onload : function(e) {
var image_file = Ti.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, "test.png");
image_file.write(this.responseData);
$.img.image = image_file.read();
},
onerror : function(e) {
alert(e.error);
},
timeout : 10000
});
client.open("GET", pngUrl);
client.send();
}
index.xml:
<Alloy>
<Window id="win" backgroundColor="gray">
<ImageView id="img" />
</Window>
</Alloy>
i have an error with the Image Upload from Facebook in my Titanium Software, everytime i want to upload an image from my App i get this:
Fail: REST API is deprecated for versions v2.1 and higher
But if i try the same code in the KitchenSink example app, it works perfect:
var xhr = Titanium.Network.createHTTPClient({
onload: function() {
// first, grab a "handle" to the file where you'll store the downloaded data
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'mygraphic.png');
f.write(this.responseData); // write to the file
var blob = f.read();
var data = {
caption: 'behold, a flower',
picture: blob
};
facebook.request('photos.upload', data, showRequestResult);
},
timeout: 10000
});
xhr.open('GET','http://www.pur-milch.de/files/www/motive/pm_motiv_kaese.jpg');
xhr.send();
And in my App:
function showRequestResult(e) {
var s = '';
if (e.success) {
s = "SUCCESS";
if (e.result) {
s += "; " + e.result;
}
} else {
s = "FAIL";
if (e.error) {
s += "; " + e.error;
}
}
alert(s);
}
Ti.App.hs_stats.addEventListener('touchend', function(e){
Ti.App.hs_stats.top = 255;
var xhr = Titanium.Network.createHTTPClient({
onload: function() {
// first, grab a "handle" to the file where you'll store the downloaded data
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'mygraphic.png');
f.write(this.responseData); // write to the file
var blob = f.read();
var data = {
caption: 'behold, a flower',
picture: blob
};
Ti.App.fb.request('photos.upload', data, showRequestResult);
},
timeout: 10000
});
xhr.open('GET','http://www.pur-milch.de/files/www/motive/pm_motiv_kaese.jpg');
xhr.send();
});
Looks like you're using the 'old' Facebook module for Appcelerator? I have image uploads working for Profiles and Pages (although Pages is a bit different, I'll explain later). Here's some quick code (I assume you already authenticated with Facebook):
var fb = require('facebook');
fb.appid = "xxxxxxxxxxxxxxxxx";
var acc = fb.getAccessToken();
fb.requestWithGraphPath('me/photos?access_token='+ acc, {picture:image, message: data}, "POST", showRequestResult);
The image variable is just a blob - It comes directly from event.media from a gallery selection or camera intent. data is the text for your status update.
In your tiapp.xml add these lines:
<property name="ti.facebook.appid">xxxxxxxxxxxxxxxxx</property>
and (if you're using Android and iOS - add both or just the platform you're using)
<modules>
<module platform="android">facebook</module>
<module platform="iphone">facebook</module>
</modules>
Now Pages were a bit strange:
var endPoint = 'https://graph.facebook.com/v2.1/' + pid + '/photos?access_token='+ acc;
xhr.open('POST',endPoint);
xhr.send({
message: data,
picture: image
});
You have to use an HTTP Request, as I couldn't get the requestWithGraphPath() to work with pages no matter what I tried.
pid is your page ID and you can get it, or a list of pages you are an admin for like so (again, create a new HTTP Request (xhr) and use this):
xhr.open("GET","https://graph.facebook.com/v2.1/me?fields=accounts{access_token,global_brand_page_name,id,picture}&access_token=" +fb.getAccessToken());
This will return the access token for each page, the global brand name (basically a clean version of the page name), it's id and the profile picture. The access token in this URL is YOUR personal access token (the &access_token= part).
As far as I can tell, these access tokens don't expire for pages, so you can save it in your app somewhere or if you REALLY want to be safe, you could grab a token before each post, but that's a bit much.
BONUS:
If you want to do video posts to pages:
var xhr = Titanium.Network.createHTTPClient();
var endPoint = 'https://graph-video.facebook.com/'+ pid +'/videos?access_token='+ acc;
xhr.open('POST',endPoint);
xhr.setRequestHeader("enctype", "multipart/form-data");
xhr.send({source:video, description:data});
and for profiles:
var acc = fb.getAccessToken();
var xhr = Titanium.Network.createHTTPClient();
var endPoint = 'https://graph-video.facebook.com/me/videos?access_token='+ acc;
xhr.open('POST',endPoint);
xhr.setRequestHeader("enctype", "multipart/form-data");
xhr.send({source:video, description:data});
video is another blob from either your camera or gallery event.media intent and data is the text you want to use for the status update.
I'm developing a mobile app for iOS and Android using Cordova and Ionic Framework. There needs to be 'Send Photo' and related functionality, and I'm using Cordova's FileTransfer to do this.
It works perfectly on iOS simulator, but throws "error code = 1" on Android device.
I know this means file_not_found or similar.
Note it happens if I take a picture from camera, or choose one from gallery.
Here is my code:
$scope.takePic = function() {
var options = {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: 0, // 0:Photo Library, 1=Camera, 2=Saved Photo Album
encodingType: 0 // 0=JPG 1=PNG
}
navigator.camera.getPicture(onSuccess, onFail, options);
}
var onSuccess = function(FILE_URI) {
window.resolveLocalFileSystemURL(FILE_URI, function(fileEntry) {
alert("full: " + JSON.stringify(fileEntry));
var realUrl = fileEntry.toURL();
$scope.picData = realUrl;
$scope.$apply();
console.log("real URL", realUrl);
});
};
var onFail = function(e) {
console.log("On fail " + e);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
Flash.success("Wysłano");
var response = JSON.parse(r.response);
$scope.attachment_id = response.data;
$scope.$apply();
$http.post($rootScope.baseServerUrl + 'Members/changeAvatar', {attachment_id: response.data}).success( function (response){
console.log(response);
});
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
$scope.send = function() {
Flash.warning('wysyłam');
var myImg = $scope.picData;
alert(myImg);
var options = new FileUploadOptions();
options.headers = {
Accept: "application/json",
Connection: "close"
}
options.fileKey="file";
options.fileName=$scope.picData.substr($scope.picData.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(myImg, encodeURI($rootScope.baseServerUrl + 'media/Attachments/add'), win, fail, options);
}
$scope.takePic and send are called by button clicks. There are a lot of alerts and console because I'm trying to find why its not working.
After picking a picture from the gallery on android I get:
file:///storage/sdcard0/download/file-name.jpg
on iOS simulator:
file:///Users//Library/Application%20Support/iPhone%20Simulator/7.1/Applications/B5FB2081-54E7-4335-8856-84C6499E6B07/tmp/cdv_photo_038.jpg
and by using this path I can show this picture by using <img src="{{picData}}"> this works on both platforms.
But if I try to send it on an Android device I get error Code = 1. On iOS sim it sends, photo, gets proper response, changes avatar...everything.
Both Cordova and plugins File and FileTransfer are up to date.
It looks like you might have a path error, file:///storage.sdcard0/download/file-name.jpg should be file:///storage/sdcard0/download/file-name.jpg if I'm not mistaken.
From perusing your code, it doesn't appear that you are parsing anything incorrectly. Maybe you want to try using an older more stable version of the file plugin if it is returning the wrong URI (and maybe file a bug report)? I haven't used the file plugin since they released 1.0, but from personal experience there have been bugs/regressions in the bleeding edge releases before.
You can target specific plugin versions from the cordova-cli using # like cordova plugin add org.apache.cordova.file#1.0.0
As well as specific tags/releases from github using # like cordova plugin add https://github.com/apache/cordova-plugin-file-transfer#r0.4.2
Maybe late but I've kinda fixed it.
In my view file I use:
<input id="file" name="file" type="file" onchange="angular.element(this).scope().addFile(this)" class="upload" accept="image/*" capture="camera"/>
so it fires $scope.addFile() from my controller as soon as you pick up file from galery:
$scope.addFile = function(item){
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
$scope.imgId = JSON.parse(evt.target.responseText).data;
$scope.$apply();
$http.post($rootScope.baseServerUrl + 'Members/changeAvatar', {attachment_id: $scope.imgId}).success( function (response){
console.log(response);
$scope.User.attachment_id = $scope.imgId;
$scope.$apply();
});
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.")
};
var updateImage = function (element) {
$scope.$apply(function() {
$scope.theFile = element.files[0];
var formData = new FormData();
formData.append("file", $scope.theFile);
var xhr = new XMLHttpRequest()
xhr.addEventListener("load", uploadComplete, false)
xhr.addEventListener("error", uploadFailed, false)
xhr.open("POST", $scope.baseServerUrl + "media/Attachments/add")
xhr.setRequestHeader("Accept","application/json")
$scope.progressVisible = true
xhr.send(formData);
});
};
updateImage(item)
}
Works for all Android devices I tested, above 4.0 excluding 4.4 because of input type="file" bug, works on iOS simulator and devices with 8.1 system (should also on older but I didn't test it).
It's not a perfect solution, because you can use only pictures you already got on your phone. I couldnt figure it out how to use Cordova FileTransfer with our server authentication way: I was always getting "please log in" in response, even when I tried adding all needed headers, tokens, anything...
So even though this solution is far from what I wanted to achieve - it works. Hope it helps anyone.
I'm able to upload an image using the the camera, but I can't seem to get the correct file name to upload (error code 1 NOT_FOUND_ERR) when trying to upload a file from my app. What I'm trying to do is upload a default profile image to server when a user first signs up.
Here is my code, which is almost identical to the working camera upload I have:
// Source
path = 'images/default.jpeg';
// Destination
var url = 'http://serverloc/data';
// Upload Options
var options = new FileUploadOptions();
options.fileKey = 'file';
options.fileName = path.substr(path.lastIndexOf('/') + 1);
options.mimeType = 'image/jpeg';
options.chunkedMode = false;
var params = new Object();
params.fullpath = path;
params.name = options.fileName;
options.params = params;
// Upload
var ft = new FileTransfer();
ft.upload(path, url,
function(result) {
// hasn't worked yet
},
function(error) {
alert('Error uploading default image: ' + error.code);
// 1 - NOT_FOUND_ERR
},
options);
Testing on Android.
Update: Since I can't this working, I guess my next best option is to add a marker property for each user, and if that propery (default-img say) is "yes", then I'll display the default image in-app, rather than having it stored on the server.
I'm trying to capture an image using the camera and upload it to my AJAX endpoint. I've confirmed that this endpoint can accept the file (I created a test HTML file on my desktop that sends a form with an image in it). I'm using Cordova (phonegap) 1.7.0, and am trying to get the fileTransfer() to work. Here is the link for the documentation that I followed:
http://docs.phonegap.com/en/1.0.0/phonegap_file_file.md.html#FileTransfer
The success callback triggers, but no $_FILES data is to be found on the endpoint.
I then found this article:
http://zacvineyard.com/blog/2011/03/25/upload-a-file-to-a-remote-server-with-phonegap/
Which suggested using options.chunkedMode = false. Now the upload takes an age and a half, before eventually failing with an error code of 3, which I believe is FileError.ABORT_ERR.
Am I missing something?
My code from the app below:
navigator.camera.getPicture(function(imageURI){
console.log('take success! uploading...');
console.log(imageURI);
var options = new FileUploadOptions();
options.fileKey = 'file';
options.fileName = 'spot_image.jpeg';
options.mimeType = 'image/jpeg';
var params = new Object();
params.spot_id = 1788;
params.param2 = 'something else';
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI,serverURL + '/ajax.php?fname=appuploadspotimage',function(r){
console.log('upload success!');
console.log(r.responseCode);
console.log(r.response);
console.log(r.bytesSent);
},function(error){
console.log('upload error')
console.log(error.code);
},options,true);
console.log('after upload');
},function(message){
console.log('fail!');
console.log(message);
},{
quality: 50,
destinationType: navigator.camera.DestinationType.DATA_URL,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
});
serverURL is defined as the domain for my AJAX endpoint, which has been whitelisted in cordova.xml.
I've seen a number of questions here in SO regarding this, which varying opinions as to whether chunkedMode should be used. Anyone having this issue as well?
Am trying this on a Samsung Galaxy S, running ICS.
May the person who helps me solve this issue mysteriously inherit a beer factory.
You can not use imageUri that you get from camera success callback in FileTransfer upload method, you have to first resolve uri as a filename like this:
navigator.camera.getPicture(function(imageURI){
window.resolveLocalFileSystemURI(imageUri, function(fileEntry) {
fileEntry.file(function(fileObj) {
var fileName = fileObj.fullPath;
//now use the fileName in your method
//ft.upload(fileName ,serverURL + '/ajax.php?fname=appuploadspotimage'...);
});
});
});
After puzzling a bit, it seems to me you can use the image uri directly....
see my answer here: (this works for me on android):
android phonegap camera and image uploading