Uploading a file to the server.

You must Login before you can answer or comment on any questions.

Hi all, I have looked at various examples on Internet on uploading the files to a php script but was not able to suceed. I have put together this script, can someone please tell where I am going wrong.

var sep = Titanium.Filesystem.getSeparator();
var uploadFile = Titanium.Filesystem.getFile(Dir.getNativePath(),filename);
var content = uploadFile.read().text;
 
var xhr = Titanium.Network.createHTTPClient();
 
xhr.addEventListener(Titanium.HTTP_DONE, function(){
    alert('done ' + this.responseText);             
});
 
xhr.addEventListener(Titanium.HTTP_STATE_CHANGED, function(){
        alert('changed '+ this.responseText);               
});
 
xhr.open('POST', "http://test.com/upload.php");
xhr.setRequestHeader("contentType", "multipart/form-data");
xhr.send({uploadedfile:content});
For PHP I have used the script given at (https://gist.github.com/1082369) .That is -
<?php
 
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name'] . ".txt"); 
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name'])." has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}
// portions of this code where borrowed from pec1985
?>

3 Answers

i try with image upload but not try with otner file ,

check this link for image upload , it help to solve your query http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-build-an-image-uploader/

Hi Vaishnav

I tried on my end :

var uploadFile = Titanium.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, "test.txt");
var content = uploadFile.read().text;
alert(content);
It is returning me the text of my file.Do the PHP script you mention accept Complete text file with .txt extension or only text of the file??

— answered 8 months ago by Jyoti Gupta
answer permalink
1 Comment
  • I was able to see the content of the file using alert. But was not able to send it to the server. It sends just the content of the file.

    — commented 8 months ago by Vaishnav Desai

When you use read().text ,it returns the CONTENT of the text file , it read file as TEXT. And if you want to directly send file with extension .txt , then use :

var uploadFile = Titanium.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, "test.txt");

xhr.send({uploadedfile:uploadFile});

Your Answer

Think you can help? Login to answer this question!