In my app, I need to download few files form server. I used the following code:
function downloadFile(index:int):void
{
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.addEventListener(Event.COMPLETE, onLoadFileComplete);
urlLoader.addEventListener(ProgressEvent.PROGRESS, onLoadFileProgress);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onURLIOError);
urlLoader.load(new URLRequest("some url"));
fileNameToSave = "some name";
trace("file name:" + fileNameToSave);
downloading = true;
}
function onLoadFileProgress(e:ProgressEvent):void
{
var loadedPct:uint = Math.round(100 * (e.bytesLoaded / e.bytesTotal));
}
function onURLIOError(e:IOErrorEvent):void
{
trace("error msg");
e.target.removeEventListener(IOErrorEvent.IO_ERROR, onURLIOError);
}
function onLoadFileComplete(e:Event):void
{
trace("File downloaded");
var file:File;
file = File.documentsDirectory.resolvePath("somelocation/" + fileNameToSave);
if(file != null)
{
var fileStream:FileStream = new FileStream();
fileStream.openAsync(file, FileMode.WRITE);
fileStream.addEventListener(OutputProgressEvent.OUTPUT_PROGRESS, outputProgressHandler);
fileStream.addEventListener(Event.CLOSE, onSaveFile);
fileStream.writeBytes(e.target.data);
fileStream.close();
}
e.currentTarget.removeEventListener(Event.COMPLETE, onLoadFileComplete);
e.currentTarget.removeEventListener(ProgressEvent.PROGRESS, onLoadFileProgress);
e.currentTarget.removeEventListener(IOErrorEvent.IO_ERROR, onURLIOError);
}
function outputProgressHandler(e:OutputProgressEvent):void
{
if (e.bytesPending == 0)
{
trace("File is completely written");
}
}
function onSaveFile(e:Event):void
{
trace("Saved Complete");
loadfiles();
e.currentTarget.removeEventListener(Event.CLOSE, onSaveFile);
}
It works fine. But the problem I'm having is when the internet is slow, sometime it triggers complete event even if the file is not fully downloaded. Is there anyway to prevent this? Any help would be appreciated.
UPDATE: Is it a good practice to use progress event to check if the download is complete rather than using complete event. Like:
if(e.bytesLoaded >= e.bytesTotal)
{
//downloadComplete
}
else
{
//not complete
}
I can not comment because I have insufficient reputation.
I have previously had similar issue where filestream write reports as complete when in fact it has not. This occurs only on older devices and occurs randomly. My testing seemed to confirm that Flash reports file saved before the OS had actually completed. When a read then occurred it would report as file not found.
I solved it rather crudely using setTimeout and repeatedly checked if the data was complete.
Related
I'm using the following code to record audio using Cordova Media plugin on android devices. This results in an empty audio file despite returning successfully on stopRecord(). Can somebody point to what might be wrong with this code?
$cordovaFile.createFile(cordova.file.dataDirectory, 'new-rec.amr'), false)
.then(function (fileObj) {
console.log('File created', fileObj);
var nativePath = fileObj.nativeURL;
resolveLocalFileSystemURL(nativePath, function (entry) {
var internalPath = entry.toInternalURL();
var mediaRec = new Media(internalPath,
//success callback
function (success) {
console.log("record success", success);
},
//error callback
function (err) {
console.log("record error: " + JSON.stringify(err));
});
// Start recording audio
mediaRec.startRecord();
});
}, function (error) {
console.log('Cannot create a file to initiate a new recording', error);
});
I was having this exact same problem today. Solved it by releasing the Media object. I'm not sure why this helped, but I have a feeling it may be that the OS is holding onto the Media object instead of saving it and then once it's released it's properly saved?
Not 100% sure though. It works without releasing in other Cordova directories (e.g. cordova.file.externalDataDirectory).
Here's my code:
var fileName = randomFileName();
fileName = fileName + ".aac";
var store = cordova.file.dataDirectory;
window.resolveLocalFileSystemURL(store, function(dir){
var directoryToSave = dir.nativeURL + fileName;
$scope.audioRecording = new Media(directoryToSave, audioRecordingSuccess, audioRecordingFail, audioStatus);
$scope.audioRecording.startRecord();
setTimeout(function(){
$scope.audioRecording.stopRecord();
$scope.audioRecording.release();
}, 5000);
});
I have serious issues loading binary image data into a simple image-element. I coded a cordova app (using Sencha touch) which loads images the following way:
xhr.open('GET', imageUrl, true);
xhr.responseType = 'blob';
xhr.addEventListener('load', function () {
if (xhr.status === 200) {
// onload needed since Google Chrome doesn't support addEventListener for FileReader
fileReader.onload = function (evt) {
image.setSrc(evt.target.result);
};
// Load blob as Data URL
fileReader.readAsDataURL(xhr.response);
}
}, false);
On Android 5 and 4.4 (these are the ones I tested) it works like a charm. Now I ran it Android 4.1 on an ASUS Tablet and the onload callback doesn't get fired. When I throw a blob in the readAsDataURL-function, at least the onload callback is fired, but the image doesn't show any image as well :(
Has anyone a suggestion, what the failure could be or what I'm doing wrong?
Ah, finally I got it to work on Android 4.1.1 (ASUS Tablet) with the following code. Another issue was, that saving an arraybuffer response from the xhr could not simply serialized, so I converted the stuff to string. Also I receive the blob taking into account, that on some systems the Blob object simply isn't there:
function arrayBufferToString(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
};
function stringToArrayBuffer(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint8Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
};
function getBlob(content, type) {
var blob = null;
// Android 4 only has the deprecated BlobBuilder :-(
try {
blob = new Blob([content], {type: type});
} catch(e) {
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder ||
window.MozBlobBuilder || window.MSBlobBuilder;
if (window.BlobBuilder)
{
var bb = new BlobBuilder();
bb.append(content);
blob = bb.getBlob(type);
}
}
return blob;
};
cachedFile = getCachedFile(...); // not of interest here, I think :-)
if (cachedFile)
{
callback.apply(this, [window.webkitURL.createObjectURL(getBlob(stringToArrayBuffer(cachedFile.data), 'image/jpeg'))]);
}
else {
xhr.open('GET', imageUrl, true);
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function () {
if (xhr.status === 200) {
cachedFile = {
url: imageUrl,
data: arrayBufferToString(xhr.response)
};
addCachedFile(cachedFile); // not of interest here, I think :-)
callback.apply(this, [window.webkitURL.createObjectURL(getBlob(xhr.response, 'image/jpeg'))]);
}
}, false);
// Send XHR
xhr.send();
}
Edit: Just did a little change and now used the Uint8Array Class instead of the Uint16Array Class because I got errors: "RangeError: byte length of Uint16Array should be a multiple of 2". Now it works well.
Edit2: Just saw, that the above code doesn't work out in all situations because of the usage of Uint8Array resp. Uint16Array.
Now I think I have a solid solution: I convert the binary responded by the image url into a base64 using canvas with the function from here http://appcropolis.com/blog/web-technology/javascript-encode-images-dataurl/ . Takes a little time, but still a working solution :)
I've been trying to run the following code but the callbacks [ok() and ko()] are not called.
Using Worklight 6.2 (Cordova 3.4).
function wlCommonInit() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
success, fail);
window.resolveLocalFileSystemURL(cordova.file.applicationDirectory
+ "www/index.html", ok, ko);
}
function ko(e) {
alert("NO");
}
function ok(fileEntry) {
alert("OK");
}
On the other hand requestFileSystem callbacks are called regularly.
The code snippet in the question will not work in Android due to a Cordova defect: https://issues.apache.org/jira/browse/CB-7273.
To progress further, it would help to understand what are your plans for the file itself.
Do you simply want the path to the file
Or do you want to alter the contents of the file?
Or?
You can read more about file system operations in Cordova in this question/answer: Where does LocalFileSystem.PERSISTENT point to?
I managed to access local fiiles in Worklight running an Android environment using a XMLHttpRequest:
//Works only on Android
function prendiCaricaRisorsaWorklight(percorsoPiuNomeFile) {
var xmlhttp = new XMLHttpRequest();
var risposta = "";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4
&& (xmlhttp.status == 200 || xmlhttp.status == 0)) {
risposta = xmlhttp.responseText;
alert(risposta);
}
}
xmlhttp.open("GET", "file:///android_asset/www/default/"
+ percorsoPiuNomeFile, true);
xmlhttp.send(null);
}
Usage example:
prendiCaricaRisorsaWorklight("css/cssInterno.css");
prendiCaricaRisorsaWorklight("js/jsInterno.js");
This shows on Android an alert with the file content.
I have the following piece of code:
function download_img(imgToDownload, imgToRemove){
var url = remote_url+imgToDownload; // image url
root_path = get_root_path();
var flag = "working";
var flag_delete = false;
var imageToDownloadPath = root_path + "/" + imgToDownload; // full file path
var imageToRemovePath = root_path + "/" + imgToRemove; // full file path
try{
var fileTransfer = new FileTransfer();
fileTransfer.download(url, imageToDownloadPath,
function () {
if(imgToRemove != "" && imgToRemove != null){
var entry = new FileEntry("foo", imageToRemovePath);
entry.remove(function (){alert("fine");flag_delete = true;}, function (){alert("marron");flag_delete = true;});
}
else{
flag_delete = true;
}
flag = "done";
},
function (error) {
flag = "done";
flag_delete = true;
}
);
}catch(error){
alert("Error capturado: "+error.message);
}
while(flag=="working" && !flag_delete){
try{
setTimeout(
function() {
/* Código */
},
300
);
}
catch(error){
alert("Error en el bucle: " + error.message);
}
}
}
I have had problems downloading the files which apparently seemed to be a sync conflict, I mean, looks like something was avorting the execution before the file/s was/were downloaded.
I have used two flags to make sure not to continue until files are downloaded (and old ones deleted if necessary). The idea is to change flag's values when the action is completed and keep the code waiting in a loop.
The results this code is giving is as follows:
It never seems to enter the success fileTransfer.download sucess method (I used an alert which never triggered) even though the first file downloads properly.
The flags are never changed so the code stays stuck in the loop, and it does not continue downloading other files.
I think it might be a very basic jQuery behaviour but I am just starting with this technologies and I am a little lost. If anyone could give me a clue on that I would really appreciate it.
Thanks!!
i am trying to do login application which takes id and password..when i click on logi button then it will connect to our local server by JSON..with the specified URL..the code is..
var loginReq = Titanium.Network.createHTTPClient();
loginReq.onload = function()
{
var json = this.responseText; alert(json);
var response = JSON.parse(json);
if (response.data.status == "success")
{ alert("Welcome ");
}
else
{ alert(response.data.status);
}
};
loginReq.onerror = function(event)
{
alert(event.toSource());
//alert("Network error");
};
loginBtn.addEventListener('click',function(e)
{ if (username.value != '' && password.value != '')
{
var url = 'our local url action=login&id='+username.value+'&pwd='+password.value;
loginReq.open("POST",url);
loginReq.send();
}
else
{
alert("Username/Password are required");
}
});
Here it is not connecting our URl..so it is entering into loginReq.onerror function...instead of loginReq.onload function..why it is throwing run time error.. The same code working fine with Iphone..
The Run Time Error is..
TypeError:Cannot call property toSource in object{'source':[Ti.Network.HttpClient],specified url} is not a function,it is a object.
This is wat the error..please let me Know...
Apparently the toSource() function does not exist in android, as it is an object. Try debugging and see what the object event contains.
You could do that by adding a line above the alert line, and adding a debug line to it.
Look in debug mode and see all variables
"toSource()" is not a documented function for either platform, and I also do not see it in the source for Titanium Mobile. If you aren't getting the error on iOS, I'm guessing it is because the error handler isn't getting called. Perhaps your emulator or device does not have internet access, whereas your iOS simulator or device does?
Regardless, error handling in the HTTPClient normally looks something like this:
loginReq.onerror = function(e)
{
Ti.API.info("ERROR " + e.error);
alert(e.error);
};