Copying a file from a server to your harddisk
Hello,
I want to copy a file from a server to my harddisk. The problem is that it's a zip file. Text files work fine, but zip files don't. I thought this could be because it's a binary file?
Any suggestions???
Rik de Vos
7 Answers
-
Accepted Answer
You're welcome!
I just went to answer another question which had the same sort of issue – turns out my example only works with small files. Tested it with a 12kb file so I didn't notice.
Trouble is the file object you pass to receive is written in chunks and in write rather than append mode. So if the file is large only the last chunk will be in the file. No option to change it to append AFAIK, but what the documentation doesn't say is that you can also pass a filestream object rather than a file object. So:
// set yourUrl to URL of zip file var userDir = $("#presetsDirH").val(); var filename = writeFileName; var writeFile = Titanium.Filesystem.getFileStream(userDir, filename); writeFile.open(Titanium.Filesystem.MODE_APPEND); var client = Titanium.Network.createHTTPClient(); client.addEventListener(Titanium.HTTP_DONE, function() { writeFile.close(); clearTimeout(timer); alert("Downloaded"); }); timer = setTimeout(function() { writeFile.close(); alert("Failed"); },10000); client.open("GET", yourUrl); client.receive(writeFile);
That should work for any size file.
-
Are you using the receive method of Titanium.Network.HTTPClient with a Titanium.Filesystem.File set as the handler?
-
This is what I use to write the file:
var userDir = $("#presetsDirH").val(); var contents = //File from server var filename = writeFileName; var writeFile = Titanium.Filesystem.getFile(userDir, filename); var writeStream = Titanium.Filesystem.getFileStream(writeFile); writeStream.open(Titanium.Filesystem.MODE_WRITE); if(writeStream.write(contents)) { installDet(""); }else { ok = "nok"; } writeStream.close();
I just have to store the file on the server in the variable contents.
-
And the contents variable is populated with the result of an XMLHttpRequest?
I'd suggest using HTTPClient instead, I tested it and successfully got a zip file saved. With your code it would be like this:
// set yourUrl to URL of zip file var userDir = $("#presetsDirH").val(); var filename = writeFileName; var writeFile = Titanium.Filesystem.getFile(userDir, filename); var client = Titanium.Network.createHTTPClient(); client.addEventListener(Titanium.HTTP_DONE, function() { alert("Downloaded"); clearTimeout(timer); }); timer = setTimeout(function() { alert("Failed"); },10000); client.open("GET", yourUrl); client.receive(writeFile);
-
Thanks! Works like a charm :)
-
The only problem is that is doesn't always work. I tried it 10 times and 6 times it wrote an incomplete file. Is this because of my server, or because of Titanium? The size of the file is only 4Kb
-
YEEEEEEEES!!!
That's it. Thankss soooo much!!!!