Multi part form-data image upload using cordova-file-transfer plugin in ios fails - ios

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

Related

MediaRecorder Blob to file in an electron app

I have an electron app that has very simple desktop capturing functionality:
const {desktopCapturer} = require('electron')
const fs = require('fs');
var recorder;
var chunks = [];
var WINDOW_TITLE = "App Title";
function startRecording() {
desktopCapturer.getSources({ types: ['window', 'screen'] }, function(error, sources) {
if (error) throw error;
for (let i = 0; i < sources.length; i++) {
let src = sources[i];
if (src.name === WINDOW_TITLE) {
navigator.webkitGetUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: src.id,
minWidth: 800,
maxWidth: 1280,
minHeight: 600,
maxHeight: 720
}
}
}, handleStream, handleUserMediaError);
return;
}
}
});
}
function handleStream(stream) {
recorder = new MediaRecorder(stream);
chunks = [];
recorder.ondataavailable = function(event) {
chunks.push(event.data);
};
recorder.start();
}
function stopRecording() {
recorder.stop();
toArrayBuffer(new Blob(chunks, {type: 'video/webm'}), function(ab) {
var buffer = toBuffer(ab);
var file = `./test.webm`;
fs.writeFile(file, buffer, function(err) {
if (err) {
console.error('Failed to save video ' + err);
} else {
console.log('Saved video: ' + file);
}
});
});
}
function handleUserMediaError(e) {
console.error('handleUserMediaError', e);
}
function toArrayBuffer(blob, cb) {
let fileReader = new FileReader();
fileReader.onload = function() {
let arrayBuffer = this.result;
cb(arrayBuffer);
};
fileReader.readAsArrayBuffer(blob);
}
function toBuffer(ab) {
let buffer = new Buffer(ab.byteLength);
let arr = new Uint8Array(ab);
for (let i = 0; i < arr.byteLength; i++) {
buffer[i] = arr[i];
}
return buffer;
}
// Record for 3.5 seconds and save to disk
startRecording();
setTimeout(function() { stopRecording() }, 3500);
I know that to save the MediaRecorder blob sources, I need to read it into an ArrayBuffer, then copy that into a normal Buffer for the file to be saved.
However, where this seems to be failing for me is combining the chunk of blobs into blobs. When the chunks are added into a single Blob - it's like they just disappear. The new Blob is empty, and every other data structure they are copied into afterwards also is completely empty.
Before creating the Blob, I know I have valid Blob's in the chunks array.
Here's what the debug info of chunks is, before executing the new Blob(chunks, {.. part.
console.log(chunks)
Then here's the debug info of the new Blob(chunks, {type: 'video/webm'}) object.
console.log(ab)
I'm completely stumped. All the reference tutorials or other SO answers I can find basically follow this flow. What am I missing?
Electron version: 1.6.2
That's not possible to be working. You didn't wait for value to come in stopReocoring. You need to change your stopRecording function to following:
function stopRecording() {
var save = function() {
console.log(blobs);
toArrayBuffer(new Blob(blobs, {type: 'video/webm'}), function(ab) {
console.log(ab);
var buffer = toBuffer(ab);
var file = `./videos/example.webm`;
fs.writeFile(file, buffer, function(err) {
if (err) {
console.error('Failed to save video ' + err);
} else {
console.log('Saved video: ' + file);
}
});
});
};
recorder.onstop = save;
recorder.stop();
}
This problem literally just fixed itself today without me changing anything. I'm not sure what about my system changed (other than a reboot) but it's now working exactly as it should.

unable to upload files using UploadCollection in SAPUI5

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.

var ft = new FileTransfer() doesnt work in iOS simulator. CordovaFileTransfer plugin issue

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

Phonegap 3.5 File Download / Moving not working

I am busy upgrading a Phonegap app from 3.3 to 3.5 everything works so far but the file download, opening isn't working
function downloadFile(url, filename, fail, downloadDone) {
window.fail = fail;
window.downloadDone = downloadDone;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function onFileSystemSuccess(
fileSystem) {
var fileTransfer = new FileTransfer();
fileTransfer.download(url, window.filePath + filename, function(theFile) {
window.downloadDone();
}, function(error) {
window.fail(error);
});
}, window.fail);
}
function setupFilePath(callBack) {
window.callback = callBack;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function onFileSystemSuccess(
fileSystem) {
fileSystem.root.getFile("dummy.html", {
create: true,
exclusive: false
}, function gotFileEntry(fileEntry) {
var sPath = fileEntry.root.replace("dummy.html", "");
window.filePath = sPath;
var fileTransfer = new FileTransfer();
fileEntry.remove();
dataDir = fileSystem.root.getDirectory(sPath + 'cordapp', {
create: true
});
window.filePath = sPath + 'cordapp/';
console.log("FILE PATH IS: " + window.filePath)
callBack()
}, null);
}, null);
}
Getting the error that the app can't create the directory what am I doing wrong? Is there also a way to not letting it backup to iCloud?

Send a recorded file via Filetransfer with Cordova/Phonegap

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.

Resources