2013-12-13 4 views
0

У меня возникает много проблем с загрузкой файлов на сервер в Titanium appcelerator. Кажется, все работает нормально, но на сервере он показывает, что произошла ошибка. Вот мой титановый код:Titanium Appcelerator загружает изображения на веб-сервер

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 

});

и код PHP на сервере:

$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!"; 
} 

Что я делаю неправильно? Любая помощь высоко ценится.

Спасибо заранее!

ответ

1

Ну, долгое время, пытаясь заставить это работать, я, наконец, нашел правильный ответ. Я поделюсь информацией для тех, кто там сталкивается с проблемами, чтобы взглянуть на них и устранить проблему с загрузкой фотографий. Я еще не тестировал Android, но все должно работать одинаково.

Вот код титаном «app.js»:

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

А вот сценарий РНР на стороне сервера. Вам нужно будет загрузить этот файл PHP на свой веб-сервер:

<?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"; 
     } 

    ?> 

И у вас оно есть. Должен сказать, что я нашел ответ на эту проблему из кулинарной книги помощника бойлера.

Я надеюсь, что это поможет кому-то, кто пытается загрузить фото на свой собственный веб-сервер в Титане.

Спасибо!

+0

привет, работающий на iOS, но не работающий на Android? ват делать? любое предложение – joe

0

image.toBlob() это вам поможет. Thanks

+0

Hi trippino. Спасибо, что нашли время, чтобы прочитать и ответить на мой вопрос. функция toBlob кажется мне, которая может быть вызвана только, если изображение прикреплено к imageView, что здесь не так. Кроме того, из моего понимания (возможно, я ошибаюсь) изображения, возвращенные из Ti.Media, уже трансформируются в blob. Я ошибаюсь? Спасибо – ito

1

onsendstream должен быть установлен перед открытием.

Смежные вопросы