2016-11-09 3 views
2

Теперь его почти 6 дней, и я пытаюсь исправить проблему с загрузкой изображений в кордове-php, но не могу ее исправить. Я попробовал несколько решений от Google и Stack Overflow. Но никто из них не работает для меня.

Я использую приведенный ниже код как передний конец.

<div> 
    <h3>Server URL for upload.php:</h3> 
    <input id="serverUrl" type="text" value="http://sample.com/mobile_app/upload_img.php" /> 
</div> 
<script type="text/javascript" charset="utf-8"> 

    var deviceReady = false; 
    /** 
    * Take picture with camera 
    */ 
    function takePicture() { 
     navigator.camera.getPicture(
      function(uri) { 
       var img = document.getElementById('camera_image'); 
       img.style.visibility = "visible"; 
       img.style.display = "block"; 
       img.src = uri; 
       document.getElementById('camera_status').innerHTML = "Success"; 
      }, 
      function(e) { 
       console.log("Error getting picture: " + e); 
       document.getElementById('camera_status').innerHTML = "Error getting picture."; 
      }, 
      { quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI}); 
    }; 
    /** 
    * Select picture from library 
    */ 
    function selectPicture() { 
     navigator.camera.getPicture(
      function(uri) { 
       var img = document.getElementById('camera_image'); 
       img.style.visibility = "visible"; 
       img.style.display = "block"; 
       img.src = uri; 
       document.getElementById('camera_status').innerHTML = "Success"; 
      }, 
      function(e) { 
       console.log("Error getting picture: " + e); 
       document.getElementById('camera_status').innerHTML = "Error getting picture."; 
      }, 
      { quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY}); 
    }; 

    /** 
    * Upload current picture 
    */ 
    function uploadPicture() { 

     // Get URI of picture to upload 
     var img = document.getElementById('camera_image'); 
     var imageURI = img.src; 
     if (!imageURI || (img.style.display == "none")) { 
      document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first."; 
      return; 
     } 

     // Verify server has been entered 
     server = document.getElementById('serverUrl').value; 
     if (server) { 

      // Specify transfer options 
      var options = new FileUploadOptions(); 
      options.fileKey="fileUpload"; 
      options.httpMethod="POST"; 
      options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1); 
      options.mimeType="image/jpeg"; 
      options.chunkedMode = false; 
    //   var op; 
//op = new FileUploadOptions(); 

      options.headers = { 
       Connection: "close" 
      }; 
      // Transfer picture to server 
      var ft = new FileTransfer(); 
      ft.upload(imageURI, server, function(r) { 
       document.getElementById('camera_status').innerHTML = "Upload successful: "+r.response+" bytes uploaded."; alert(r.response);    
      }, function(error) { 
       alert(r.response); 
       document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;    
      }, options); 
     } 
    } 
    /** 
    * View pictures uploaded to the server 
    */ 
    function viewUploadedPictures() { 

     // Get server URL 
     server = document.getElementById('serverUrl').value; 
     if (server) { 

      // Get HTML that lists all pictures on server using XHR 
      var xmlhttp = new XMLHttpRequest(); 
      // Callback function when XMLHttpRequest is ready 
      xmlhttp.onreadystatechange=function(){ 
       if(xmlhttp.readyState === 4){ 
        // HTML is returned, which has pictures to display 
        if (xmlhttp.status === 200) { 
         document.getElementById('server_images').innerHTML = xmlhttp.responseText; 
        } 
        // If error 
        else { 
         document.getElementById('server_images').innerHTML = "Error retrieving pictures from server."; 
        } 
       } 
      }; 
      xmlhttp.open("GET", server , true); 
      xmlhttp.send();   
     } 
    } 

    /** 
    * Function called when page has finished loading. 
    */ 
    function init() { 
     document.addEventListener("deviceready", function() {deviceReady = true;}, false); 
     window.setTimeout(function() { 
      if (!deviceReady) { 
       alert("Error: PhoneGap did not initialize. Demo will not run correctly."); 
      } 
     },2000); 
    } 
    </script> 

И вот код бэкэнда (PHP).

<?php 
header("Access-Control-Allow-Origin: *"); 
//header("Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS"); 
header("content-type: image/png"); 
// Directory where uploaded images are saved 
$dirname = "user_img";//"mobile_app/user_img"; 
var_dump($_POST); 
$new_image_name = urldecode($_FILES["fileUpload"]["name"]).".png"; 
// If uploading file 
//echo $_FILES; 
echo $new_image_name; 
print_r($_FILES["fileUpload"]); 
if ($_FILES) { 
    print_r($_FILES); 
    //mkdir ($dirname, 0777, true); 
    move_uploaded_file($_FILES["fileUpload"]["tmp_name"],$dirname."/".$_FILES["fileUpload"]["name"]); 
} 
// If retrieving an image 
else if (isset($_GET['image'])) { 
    $file = $dirname."/".$_GET['image']; 
    // Specify as jpeg 
    header('Content-type: image/jpeg'); 

    // Resize image for mobile 
    list($width, $height) = getimagesize($file); 
    $newWidth = 120.0; 
    $size = $newWidth/$width; 
    $newHeight = $height * $size; 
    $resizedImage = imagecreatetruecolor($newWidth, $newHeight); 
    $image = imagecreatefromjpeg($file); 
    imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 
    imagejpeg($resizedImage, null, 80); 
} 
// If displaying images 
else { 
    $baseURI = "http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI']; 
    $images = scandir($dirname); 
    $ignore = Array(".", ".."); 
    if ($images) { 
     foreach($images as $curimg){ 
      if (!in_array($curimg, $ignore)) { 
       echo "Image: ".$curimg."<br>"; 
       echo "<img src='".$baseURI."?image=".$curimg."&rnd=".uniqid()."'><br>"; 
      } 
     } 
    } 
    else { 
     echo "No images on server"; 
    } 
} 
?> 

Я нашел $_FILES пуст Я получаю Array() только. Я не знаю, что не так с кодом, потому что тот же код я видел по нескольким вопросам и примерам.

Я использовал два веб-сервера, но тот же результат.

Папка user_img имеет доступ 777.

+0

Что такое ** запрос ** тип контента? ('var_dump ($ _ SERVER ['HTTP_CONTENT_TYPE']);') –

+0

Я получаю NULL. i добавил заголовок («content-type: image/jpeg»); в заголовке, но он по-прежнему равен нулю. – Ironic

ответ

1

И наконец, через 7 дней я исправил проблему. На самом деле я был очень глуп. Вы будете смеяться надо мной.

Адрес, который я дал, был http://sample.com/upload_img.php Мне просто нужно добавить www в URL. Итак, рабочий URL-адрес: http://www/sample.com/upload_img.php. Устранена проблема.

Я надеюсь, что кто-то другой получит помощь от этого.

+0

Это [дубликат вашего ответа здесь] (https://stackoverflow.com/a/40560981/472495). – halfer

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