I am having a lot of issues trying to upload files to the server in Titanium appcelerator. All seems to work fine, but in the server it shows that an error has occurred. Here's my Titanium code:
var win = Ti.UI.createWindow({
backgroundColor : "#FFF"
});
var ind = Titanium.UI.createProgressBar({
width : 200,
height : 50,
min : 0,
max : 1,
value : 0,
style : Titanium.UI.iPhone.ProgressBarStyle.PLAIN,
top : 10,
message : 'Uploading Image',
font : {
fontSize : 12,
fontWeight : 'bold'
},
color : '#888'
});
win.add(ind);
ind.show();
win.open();
Titanium.Media.openPhotoGallery({
success : function(event) {
alert("success! event: " + JSON.stringify(event));
var image = event.media;
var xhr = Titanium.Network.createHTTPClient();
xhr.onerror = function(e) {
Ti.API.info('IN ERROR ' + e.error);
};
xhr.onload = function() {
Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
};
xhr.onsendstream = function(e) {
ind.value = e.progress;
//Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress + ' ' + this.status + ' ' + this.readyState);
};
// open the client
xhr.open('POST', 'http://mypathtotheserver/myphpuploaderfile.php');
xhr.setRequestHeader("Connection", "close");
// send the data
xhr.send({
media : image
});
},
cancel : function() {
},
error : function(error) {
},
allowImageEditing : true
});
and the php code in the server:
$target_path = "uploads/";
$target_path = $target_path . $_FILES['media']['name'];
if(move_uploaded_file($_FILES['media']['tmp_name'],$target_path)) {
echo "The file ". basename( $_FILES['media']['name']).
" has been uploaded";
}
else
{
echo "There was an error uploading the file, please try again!";
}
What am I doing wrong? Any help is highly appreciated.
Thank you in advance!
onsendstream must be set before the open.
Well after spending a long time trying to get this to work, I finally found the correct answer. I will share here for anyone out there running into issues to take a look and fix the photo upload problem. I haven't tested using Android yet, but it should all work the same.
Here's the titanium 'app.js' code:
var win = Ti.UI.createWindow({
backgroundColor : "#FFF"
});
var ind = Titanium.UI.createProgressBar({
width : 200,
height : 50,
min : 0,
max : 1,
value : 0,
style : Titanium.UI.iPhone.ProgressBarStyle.PLAIN,
top : 10,
message : 'Uploading Image',
font : {
fontSize : 12,
fontWeight : 'bold'
},
color : '#888'
});
win.add(ind);
ind.show();
win.open();
//Not a necessary function, but just in case you want to randomly create names
// for each photo to be uploaded
function randomString(length, current) {
current = current ? current : '';
return length ? randomString(--length, "abcdefghiklmnopqrstuvwxyz".charAt(Math.floor(Math.random() * 60)) + current) : current;
}
Titanium.Media.openPhotoGallery({
success : function(event) {
var image = event.media;
var xhr = Titanium.Network.createHTTPClient();
xhr.open('POST', 'http://yoursite.com/scriptsfolder/upload.php');
xhr.onerror = function(e) {
Ti.API.info('IN ERROR ' + e.error);
};
xhr.onload = function(response) {
if ( this.responseText !=0){
var imageURL = this.responseText;
alert('Your image was uploaded to ' +imageURL);
}else {
alert("The upload did not work! Check your PHP server settings.");
}
};
xhr.onsendstream = function(e) {
ind.value = e.progress;
};
// send the data
var r = randomString(5) + '.jpg';
xhr.send({
'media': image,
'randomFilename' : r
});
},
cancel : function() {
},
error : function(error) {
},
allowImageEditing : true
});
And here is the PHP server-side script. You will need to upload this PHP file to your webserver:
<?php
$target = getcwd();
$target = $target .'/'. $_POST['randomFilename'];
if (move_uploaded_file($_FILES['media']['tmp_name'], $target)) {
$filename = $target;
//Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);
// The x and y coordinates on the original image where we will begin cropping the image
$left = 0;
$top = 0;
//This will be the final size of the image (e.g how many pixesl left and down we will be doing)
$crop_width = $current_width;
$crop_height = $current_height;
//Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename, 100);
echo 'http://yoursite.com/scriptsfolder/'.$_POST['randomFilename'];
}else {
echo "0";
}
?>
And there you have it. I have to say that I found the answer to this problem from boydlee's appcelerator cookbook.
I hope this helps someone who is struggling to get photo upload to their own webserver in Titanium.
Thanks!
use image.toBlob() it help you.
Thanks
Related
I have to upload an image to server using multi-part image upload from my ionic project. Here is my code,
$scope.uploadImage = function(imageUrl) {
var fileName = imageUrl.substring(imageUrl.lastIndexOf('/')+1);
var json= {
"id":123,
"name" :fileName
}
var fileUploadOptions = new FileUploadOptions();
fileUploadOptions.fileKey="file";
fileUploadOptions.fileName = fileName;
fileUploadOptions.params = {
json : json
};
fileUploadOptions.mimeType="image/jpeg";
var URL = 'http://192.168.43.7:8080/services/uploadImage'
var encodedURI = encodeURI(URL);
console.log('fileUploadOptions : ',fileUploadOptions);
var ft = new FileTransfer();
ft.upload(imageUrl, encodedURI, onSuccess, onError, fileUploadOptions, false);
function onSuccess(response){
console.log('file uploaded: ',response);
}
function onError(error){
console.log('upload failed',error);
}
}
I am using the following plugins
cordova-plugin-file
cordova-plugin-file-transfer
cordova-plugin-camera
My image capture code is
$scope.takePhoto = function() {
var options = {
quality: 75,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: 1,
allowEdit: false,
encodingType: 0,
targetWidth: 1280,
targetHeight: 720,
popoverOptions: CameraPopoverOptions,
direction: 1,
saveToPhotoAlbum: true
};
var cameraSuccess = function(imageData) {
onPhotoURISuccess(imageData);
function onPhotoURISuccess(imageURI) {
createFileEntry(imageURI);
}
function createFileEntry(imageURI) {
window.resolveLocalFileSystemURL(imageURI, copyPhoto, fail);
}
function copyPhoto(fileEntry) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
fileSys.root.getDirectory("photos", { create: true, exclusive: false }, function(dir) {
var fileName = 12 + "_" + 56 + "_" + 67 + ".jpg";
fileEntry.copyTo(dir, fileName, onCopySuccess, fail);
}, fail);
}, fail);
}
function onCopySuccess(entry) {
console.log('Full path: ', JSON.stringify(entry));
var path = entry.toURL();
$scope.imageUrl = path;
console.log('imageUrl: ',$scope.imageUrl);
}
function fail(error) {
console.error(JSON.stringify(error));
var cause = "";
if (error.code == 20) {
cause = "Camera permission denied"
}
}
}
var cameraError = function(error) {
console.log('camera error: ', error);
}
navigator.camera.getPicture(cameraSuccess, cameraError, options);
}
I am passing the $scope.imageUrl variable to upload function.
The code works fine in android devices.
But iOS, the upload fails.
I am getting
com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
error in my server console.
In my device console I am getting the following error,
upload failed
body: "An error has occurred. Please contact system administrator."
code: 3
exception: null
http_status: 500
source: "file:///var/mobile/Containers/Data/Application/8C4518AC-5606-4806-A8D2-216125EFE725/Documents/photos/12_56_57.jpg"
target: "http://192.168.43.7:8080/services/uploadImage"
The message in the body of the error is from my server.
As per the error I get from server, I came to know that, the JSON part is not getting uploaded to server. I tried to recreate the same issue with postman without sending the JSON object. I got the same error.
Do anyone know what is the issue ? Why only in iOS device this issue is there ?
From the docs:
params: A set of optional key/value pairs to pass in the HTTP request. (Object, key/value - DOMString)
Try using fileUploadOptions.params = { json : JSON.stringify(json) } instead.
var imageUrI="file:///storage/emulated/0/newfile.csv";
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg/csv";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://fileupload/admin/add_image_my.php",
function (result) {
console.log(JSON.stringify(result));
},
function (error) {
console.log(JSON.stringify(error));
}, options);
I am receiving 403 Forbidden error when I try to upload a file using UploadCollection.
The code in my view.js is:
var oOUpload = new sap.m.UploadCollection("oinspupload",{
multiple : true,
sameFilenameAllowed : true,
instantUpload : false,
uploadUrl : "/sap/opu/odata/sap/ZACCBILL_SRV/FileSet",
/* uploadComplete : function(oEvent){
//alert ("File Uploaded successfully");
// oController.fileUpload(oEvent);
}, */
fileDeleted : function(oEvent){
oController.fileDelete(oEvent);
},
fileRenamed : function(oEvent){
alert ("File renamed successfully");
//oController.fileRename(oEvent);
}
});
The code in my view.controller is:
OData.request({
requestUri : sServiceUrl,
method : "GET",
headers :
{
"X-Requested-With" : "XMLHttpRequest",
"Content-Type" : "application/atom+xml",
"DataServiceVersion" : "2.0",
"Authorization" : AuthToken,
"X-CSRF-Token" : "Fetch"
}
},
function(data, response) {
debugger;
if(sap.ui.Device.browser.chrome || sap.ui.Device.browser.msie || sap.ui.Device.browser.safari){
header_xcsrf_token = response.headers['x-csrf-token'];
}else if(sap.ui.Device.browser.firefox){
header_xcsrf_token = response.headers['X-CSRF-Token'];
}
xcsrf_token_ref.header_xcsrf_token = header_xcsrf_token;
csrftoken = xcsrf_token_ref.header_xcsrf_token;
debugger;
uploadattachments(xcsrf_token_ref);
},
function(err) {
debugger;
var request = err.request; // the request that was sent.
var response = err.response; // the response that was received.
alert("Error in Get -- Request "
+ request + " Response "
+ response);
});
function uploadattachments(token){
debugger;
var uploader;
uploader= sap.ui.getCore().byId("oinspupload");
var aItems = uploader.getItems();
var slug, sequence;
for (i = 0; i < aItems.length; i++) {
sequence = i + 1;
slug = "CONTAINERID1000040100;STATUSIB;SEQUENCE" + sequence+ ";FILENAMECamera.png" ;
uploader.addHeaderParameter(new sap.m.UploadCollectionParameter({name: "slug", value: slug }));
debugger;
uploader.addHeaderParameter(new sap.m.UploadCollectionParameter({name: "X-Csrf-Token", value: token.header_xcsrf_token }));
uploader.upload();
}
}
Please don't mind the missing parenthesis as the code above is not the complete code.
The above code works fine with fileuploader. I am sure the issue is that the uploadcollection is not passing the fetched CSRF Token properly but I am unable to figure out what's wrong.
Finally Found the solution myself with the help of the following blog
http://scn.sap.com/community/developer-center/front-end/blog/2016/03/29/using-the-uploadcollection-to-uploaddownload-archivelink-files-via-gateway
Upload Collection only works with instantUpload as true and does not work with instantUpload as false as of version 1.32.X. UploadCollection is Buggy and is yet to be rectified in the future versions. Also the CSRF token validation needs to be done in the change event. Below is the code:
View.js
var oOUpload = new sap.m.UploadCollection("oinspupload",{
multiple : true,
sameFilenameAllowed : false,
instantUpload : true,
uploadUrl : "/sap/opu/odata/sap/ZACCBILL_SRV/FileSet",
fileDeleted : function(oEvent){
oController.fileDelete(oEvent);
},
fileRenamed : function(oEvent){
alert ("File renamed successfully");
},
change: function(oEvent) {
debugger;
csrftoken = xcsrf_token_ref.header_xcsrf_token;
var oUploadCollection = oEvent.getSource();
var oCustomerHeaderToken = new sap.m.UploadCollectionParameter({
name : "x-csrf-token",
value : csrftoken
});
oUploadCollection.addHeaderParameter(oCustomerHeaderToken);
},
});
All header params must be added from "change" function. If you add it after, they won't be recieved on Backend.
Also, It is possible upload files with instantUpload=false. You only need bind uploadUrl parameter with a paremeter of view's model, and dynamically, it will change when you change the url.
For example:
View element:
<UploadCollection instantUpload="false" uploadUrl="{ResourceModel>/sServiceUrl}"/>
Controller onInitFunction:
var resourcemodel = this.getOwnerComponent().getModel("ZGW_PURCHREQ_01_SRV");
var oDataResource = {
sServiceUrl: resourcemodel.sServiceUrl + "/FileSet"
};
var jsonResource = new JSONModel(oDataResource);
this.getView().setModel(jsonResource, "ResourceModel");
When you fire upload, it will send a petition to uploadUrl defined on "sServiceUrl" of "ResourceModel".
Other option is set upload url and/or new header params before fire upload function with:
var oUploadCollection = this.getView().byId("UploadCollection");
var sServiceUrl = resourcemodel.sServiceUrl + "/FileSet";
var headerBanfn = null;
for (var i = 0; i < oUploadCollection._aFileUploadersForPendingUpload.length; i++) {
headerBanfn = new sap.ui.unified.FileUploaderParameter({
name: "banfn",
value: "123456"
});
oUploadCollection._aFileUploadersForPendingUpload[i].setUploadUrl(sServiceUrl);
oUploadCollection._aFileUploadersForPendingUpload[i].addHeaderParameter(headerBanfn);
}
oUploadCollection.upload();
I hope it was useful.
I want to upload my image from my photo gallery in ios simulator to my amzazon s3 bucket. This code works fine on android but refuses to work on iOS and im not sure why
code to select photo from image gallery
$scope.choosePhoto = function(index) {
var options = {
destinationType : Camera.DestinationType.FILE_URL,
sourceType : Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit : false,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions,
mediaType: Camera.MediaType.PICTURE,
correctOrientation: true
};
// 3
$cordovaCamera.getPicture(options).then(function(imageData) {
// 4
var imagetype;
onImageSuccess(imageData);
function onImageSuccess(fileURI) {
createFileEntry(fileURI);
}
function createFileEntry(fileURI) {
window.resolveLocalFileSystemURL(fileURI, copyFile, fail);
}
// 5
function copyFile(fileEntry) {
var name = fileEntry.fullPath.substr(fileEntry.fullPath.lastIndexOf('/') + 1);
var newName = (new Date()).getTime() + name;
halfthru(fileEntry, newName); //diff
getImageType(fileEntry); //diff
}
function getImageType(fileEntry) { //diff
var typeImage;
$scope.$evalAsync(function() {
fileEntry.file(function(file){
typeImage= file.type;
$scope.imagelist = typeImage;
imagetype = typeImage;
}, function(e){
});
})
}
function halfthru(fileEntry, newName) {
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(fileSystem2) {
fileEntry.copyTo(
fileSystem2,
newName,
onCopySuccess,
fail
);
}, fail);
}
// 6
function onCopySuccess(entry) {
$scope.activeSlide = index;
$scope.modal1.show();
$scope.$evalAsync($scope.images.push({file: entry.nativeURL, type: $scope.imagelist}));
imagesModalCount = $scope.images.length;
attachedImageCount = $scope.imagesAttached.length;
$scope.$on('$destroy', function() {
$scope.modal1.remove();
});
}
function fail(error) {
}
}, function(err) {
});
}
code to upload to amazon
$scope.uploadImage = function(imageURI, fileName) {
var deferred = $q.defer();
createCase.getAws().then(function(awsDetails) {
var policy = awsDetails.policy;
var signature = awsDetails.signature;
var key = awsDetails.key;
var datenow = awsDetails.datenow;
var s3URI = encodeURI("https://partners-mobile-app.s3.amazonaws.com/"),
awsKey = key,
policyBase64 = policy,
acl = "public-read";
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileName;
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.headers = {
Connection: "close"
};
options.params = {
"key": fileName,
"AWSAccessKeyId": key,
"acl": acl,
"policy": policyBase64,
"signature": signature,
"Content-Type": "image/jpeg"
};
var f = ft.upload(imageURI, s3URI,
function (e) {
console.log("uploadimage: "+ imageURI)
console.log("uploads3uri: "+ s3URI)
console.log("im in upload now")
$scope.finalimagelist.push(s3URI+fileName);
if($scope.finalimagelist.length === $scope.images.length){
console.log("OK SER GO")
deferred.resolve($scope.finalimagelist);
}
},
function (e) {
deferred.reject(e);
},
options);
}
SO basically, i choose the image from image gallery and then upload to amazon everythg looks good but it just doesnt upload the image and i dont know why.
I am using AngularJS and the plugin cordova-plugin-file-transfer
my info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Please have a look to this. This whole thing sounds to me like a problem with ATS / Apple Transport Security on iOS 9
This would be the solution for it:
https://stackoverflow.com/a/32710127/3671726
I am trying to send a voice recording that I recorded via the Media plugin.
When I try to send the file I get this FileError.NOT_FOUND_ERR error:
Error opening file /myRecording100.wav: Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0xa358640 {NSFilePath=/myRecording100.wav, NSUnderlyingError=0xa34fb30 "The operation couldn’t be completed. No such file or directory"}
2014-08-06 17:02:26.919 Bring Me[40961:c07] FileTransferError {
code = 1;
source = "/myRecording100.wav";
target = "http://XXXX.xom";
}
However, I can play the voice recording after recording it.
Why would I be able to play the file (showing that the file was recorded and saved correctly) but FileTransfer be unable to send it?
Here is my code (for ios):
var my_recorder = null;
var mediaFileFullName = null; // iOS
var mediaRecFile = "myRecording100.wav";
var checkFileOnly = false;
/******
Call when start recording
******/
function startRecording() {
checkFileOnly = false;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccessFileSystem, function() {
console.log("***test: failed in creating media file in requestFileSystem");
});
}
function onSuccessFileSystem(fileSystem) {
if (checkFileOnly === true) {
// Get File and send
fileSystem.root.getFile(mediaRecFile, { create: false, exclusive: false }, onOK_GetFile, onFail_GetFile);
}
else {
// Create File
fileSystem.root.getFile(mediaRecFile, { create: true, exclusive: false }, onOK_SaveFile, onFail_GetFile);
}
}
/* Save the file*/
function onOK_SaveFile(fileEntry) {
mediaFileFullName = fileEntry.fullPath;
my_recorder = new Media(mediaFileFullName,
function() { document.location ="address_form.html"; // Redirect the user to an other page },
function(err) { console.log("playAudio():callback Record Error: "+err);}
);
my_recorder.startRecord();
}
/* Get the file and send it */
function onOK_GetFile(fileEntry) {
mediaFileFullName = fileEntry.fullPath;
/*
// Read the recorded file is WORKING !
my_player = new Media(mediaFileFullName, onMediaCallSuccess, onMediaCallError);
my_player.play();
*/
var options = new FileUploadOptions();
options.fileKey = "want";
options.fileName = "file.wav";
options.mimeType = "audio/wav";
options.chunkedMode = false;
options.params = parameters;
var ft = new FileTransfer();
ft.upload(mediaFileFullName, "https://SERVER_ADDRESS", win, fail, options);
}
/******
Called when stop recording
******/
function stopRecording() {
if (my_recorder) {
my_recorder.stopRecord();
}
}
Since the v1.0 of File plugin, to upload a file in the filesystem via the file-transfer plugin, you'll need to use the .toURL() method to access to it.
If you are upgrading to a new (1.0.0 or newer) version of File, and
you have previously been using entry.fullPath as arguments to
download() or upload(), then you will need to change your code to use
filesystem URLs instead.
FileEntry.toURL() and DirectoryEntry.toURL() return a filesystem URL
of the form
So the correct code is :
/* Get the file and send it */
function onOK_GetFile(fileEntry) {
var options = new FileUploadOptions();
options.fileKey = "want";
options.fileName = "file.wav";
options.mimeType = "audio/wav";
options.chunkedMode = false;
options.params = parameters;
var ft = new FileTransfer();
ft.upload(fileEntry.toURL(), "https://SERVER_ADDRESS", win, fail, options);
}
I got the exact same issue on iOS,and FileUploadOptions didn't work for me.
In case someone is struggling as well, the solution for me has been to switch to LocalFileSystem.Temporary.
Here there is a snippet which shows a full example (not tested on Android):
var accessType = LocalFileSystem.TEMPORARY; // It was LocalFileSystem.PERSISTENT;
/** Utility function to return a fileEntry together with the metadata. */
var getFile = function(name, create, successCallback, failCallback) {
WL.Logger.debug("Request for file " + name + " received, create is " + create + ".");
var onSuccessFileSystem = function(fileSystem) {
fileSystem.root.getFile(name, { create: create, exclusive: false },
function(fileEntry){
WL.Logger.debug("Success, file entry for " + name + " is " + JSON.stringify(fileEntry));
fileEntry.getMetadata(function(metadata){
WL.Logger.debug("File entry " + name + " metadata is: " + JSON.stringify(metadata));
successCallback(fileEntry, metadata);
}, function(err) {
WL.Logger.debug("Fail to retrieve metadata, error: " + JSON.stringify(err));
if(failCallback) failCallback(err);
});
},
function(err) {
WL.Logger.error("Failed to retrieve the media file " + name + ".");
if(failCallback) failCallback(err);
});
}
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(accessType, 0, onSuccessFileSystem, function(err) {
WL.Logger.error("Failed to access file system.");
if(failCallback) failCallback(err);
});
};
var Recorder = declare([ ], {
mediaSrc : null,
mediaObj : null,
constructor : function(data, domNode){
this.mediaSrc = "new_recording.wav";
},
startRecord : function() {
var self = this;
var startRecording = function(source) {
var onMediaCallSuccess = function() { WL.Logger.debug("Media object success."); };
var onMediaCallError = function(err) { WL.Logger.error("Error on the media object: " + JSON.stringify(err)); };
self.mediaObj = new Media(source, onMediaCallSuccess, onMediaCallError);
self.mediaObj.startRecord();
};
// On iOS, first I need to create the file and then I can record.
if (deviceCheck.phone.ios) {
WL.Logger.debug("iOS detected, making sure the file exists.");
getFile(this.mediaSrc, true, function(fileEntry){ startRecording(fileEntry.fullPath); });
} else {
if (!deviceCheck.phone.android)
WL.Logger.warn("Don't know the device, trying to record ...");
else
WL.Logger.debug("Android detected.");
startRecording(this.mediaSrc);
}
},
stopRecord : function() {
this.mediaObj.stopRecord();
this.mediaObj.release();
},
play: function() {
var p,
playSuccess = function() { WL.Logger.debug("Play success."); p.release(); },
playFail = function() { WL.Logger.debug("Play fail."); };
p = new Media(this.mediaSrc, playSuccess, playFail);
p.play();
},
getData : function(successCallback, failCallback) {
var fileName = (deviceCheck.phone.android ? "/sdcard/" : "") + this.mediaSrc;
WL.Logger.debug("Asking for the file entry ... ");
getFile(this.mediaSrc, false,
function(fileEntry, metadata) {
WL.Logger.debug("Success: I found a file entry: " + fileEntry.nativeURL + ", size is " + metadata.size);
fileEntry.file(function(file) {
WL.Logger.debug("Success: file retrieved!");
var reader = new FileReader();
reader.onloadend = function(evt) {
WL.Logger.debug("Sending content and event data to success callback.");
successCallback(this.result, metadata, evt);
};
reader.readAsDataURL(file);
}, function(err){
WL.Logger.error("Error: Impossible to retrieve the file");
failCallback(err);
})
}, function(err){
WL.Logger.error("Fail: no file entry found: " + JSON.stringify(err));
failCallback(err);
});
}
});
There is a bit of Worklight (debug output) and dojo (declare), but this code could be useful as reference.
Hello I Want to upload a powerpoint file using phonegap file transfer protocol to my local java server thru ios simulator, the location of the file on the phone is passed to the handleOpenURL function when the user selects to open a powerpoint with my app. The problem is that nothing is happening although im sure this method is executing??!! can anyone help please?
function handleOpenURL(url)
{
setTimeout(function() {
alert(url);
jQuery.get( "http://192.168.1.100:8080/PpServer/getnumberofslides" , function( data ) {
numberofslides=data;
alert( "Load was performed." + data );
});
fileURL = url;
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
// processapplication();
}
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);
}
var uri = encodeURI("http://192.168.1.100:8080/NewServerlet");
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType="multipart/form-data";
options.httpMethod="Post"
// options.params = {"file"};
var headers={'headerParam':'file'};
// options.headers = headers;
var ft = new FileTransfer();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
} else {
loadingStatus.increment();
}
};
ft.upload(fileURL, uri, win, fail, options);
}, 0);
//
}