$_files 在Phonegap/Cordova 中的图像上传中为空 [英] $_files is empty in image upload in Phonegap/Cordova

查看:31
本文介绍了$_files 在Phonegap/Cordova 中的图像上传中为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在快 6 天了,我正在尝试修复 cordova-php 中的图片上传问题,但无法修复.我尝试了来自 Google 和 Stack Overflow 的多种解决方案.但它们都不适合我.

我使用以下代码作为前端.

<h3>upload.php 的服务器 URL:</h3><input id="serverUrl" type="text" value="http://sample.com/mobile_app/upload_img.php"/>

<script type="text/javascript" charset="utf-8">var deviceReady = false;/*** 用相机拍照*/函数 takePicture() {navigator.camera.getPicture(函数(uri){var img = document.getElementById('camera_image');img.style.visibility = "可见";img.style.display = "块";img.src = uri;document.getElementById('camera_status').innerHTML = "成功";},功能(e){console.log("获取图片出错:" + e);document.getElementById('camera_status').innerHTML = "获取图片时出错.";},{ 质量:50,目的地类型:navigator.camera.DestinationType.FILE_URI});};/*** 从库中选择图片*/功能选择图片(){navigator.camera.getPicture(函数(uri){var img = document.getElementById('camera_image');img.style.visibility = "可见";img.style.display = "块";img.src = uri;document.getElementById('camera_status').innerHTML = "成功";},功能(e){console.log("获取图片出错:" + e);document.getElementById('camera_status').innerHTML = "获取图片时出错.";},{ 质量:50,目的地类型:navigator.camera.DestinationType.FILE_URI,源类型:navigator.camera.PictureSourceType.PHOTOLIBRARY});};/*** 上传当前图片*/函数上传图片(){//获取要上传的图片的URIvar img = document.getElementById('camera_image');var imageURI = img.src;if (!imageURI || (img.style.display == "none")) {document.getElementById('camera_status').innerHTML = "先拍照或从库中选择图片.";返回;}//验证服务器是否已进入server = document.getElementById('serverUrl').value;如果(服务器){//指定传输选项var options = new FileUploadOptions();options.fileKey="文件上传";options.httpMethod="POST";options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);options.mimeType="图像/jpeg";options.chunkedMode = false;//变量操作;//op = new FileUploadOptions();options.headers = {连接:关闭"};//将图片传输到服务器var ft = new FileTransfer();ft.upload(imageURI,服务器,功能(r){document.getElementById('camera_status').innerHTML = "上传成功:"+r.response+" 已上传字节数.";警报(r.response);}, 函数(错误){警报(r.response);document.getElementById('camera_status').innerHTML = "上传失败:代码 = "+error.code;}, 选项);}}/*** 查看上传到服务器的图片*/函数 viewUploadedPictures() {//获取服务器地址server = document.getElementById('serverUrl').value;如果(服务器){//使用 XHR 获取列出服务器上所有图片的 HTMLvar xmlhttp = new XMLHttpRequest();//XMLHttpRequest 就绪时的回调函数xmlhttp.onreadystatechange=function(){如果(xmlhttp.readyState === 4){//返回HTML,有图片显示如果(xmlhttp.status === 200){document.getElementById('server_images').innerHTML = xmlhttp.responseText;}//如果出错别的 {document.getElementById('server_images').innerHTML = "从服务器检索图片时出错.";}}};xmlhttp.open("GET", server , true);xmlhttp.send();}}/*** 页面加载完成后调用的函数.*/函数初始化(){document.addEventListener("deviceready", function() {deviceReady = true;}, false);window.setTimeout(function() {如果(!设备就绪){alert("错误:PhoneGap 没有初始化.Demo 无法正常运行.");}},2000);}

这里是后端 (PHP) 代码.

我发现 $_FILES 是空的,我只得到 Array().我不知道代码有什么问题,因为我在多个问题和示例中看到过相同的代码.

我使用了两个 Web 服务器,但结果相同.

user_img 文件夹有 777 访问权限.

解决方案

最后我解决了这个问题,修复很简单.

我提供的网址是 http://sample.com/upload_img.php.我只需要在网址中添加 www .因此,工作 URL 是 http://www/sample.com/upload_img.php.它解决了这个问题.

Now its almost 6 days and I am trying to fix image upload issue in cordova-php but not able to fix it. I tried multiple solutions from Google and Stack Overflow. But none of them is working for me.

I am using the below code as front end.

<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>

And here comes the backend (PHP) code.

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

I found $_FILES is empty I am getting Array() only. I don't know what is wrong with the code because same code i have seen on multiple question and examples.

I used two web servers but same result.

user_img folder have 777 access.

解决方案

Finally I fixed the issue, the fix was simple.

The url I had given was http://sample.com/upload_img.php. I just needed to add www in the url. So, working URL is http://www/sample.com/upload_img.php. It fixed the issue.

这篇关于$_files 在Phonegap/Cordova 中的图像上传中为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆