javascript - Phonegap/Cordova 中的图像上传中 $_files 为空

标签 javascript php cordova phonegap-plugins

现在已经快 6 天了,我正在尝试修复 cordova-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 访问权限。

最佳答案

终于解决了这个问题,解决起来很简单。

我给出的网址是http://sample.com/upload_img.php。我只需要在 url 中添加 www 即可。因此,工作 URL 为 http://www/sample.com/upload_img.php。 它解决了这个问题。

关于javascript - Phonegap/Cordova 中的图像上传中 $_files 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40479000/

相关文章:

javascript - 使用javascript限制输入标签中的数值

javascript - 如果在下拉列表中选择某个项目,如何创建文本框?

javascript - 使用透明系列时 Highcharts 栏缩放问题

javascript - 如何确保 div 中的内容不会被附加到 div 底部的粘性元素 chop ?

php - 使用数据库和碳中的日期获取特定年龄的用户

php - 使用 Android 更新 MySQL 数据库中的现有数据

php - htaccess RewriteRule 读取文档根目录之外的图像

javascript - 如何修复 PhoneGap 构建错误?

javascript - Cordova 应用程序中 HTML 元素中存储的数据的有效性

cordova - 配置 Meteor 移动应用程序以在运行时连接到不同的服务器