遍历$ _FILES会导致JSON意外令牌

时间:2019-02-22 13:38:17

标签: php json

*****更新:**我认为dSubmit函数存在问题,它可能无法处理多部分表单数据,因此导致在执行foreach时PHP引发错误?我已经通过函数提交了数组,没有问题,文件是否有所不同[]

我在网站上提交了AJAX表单,返回的JSON数组用于显示消息或定向到另一个页面。一切运行良好,直到我遍历通过PHP脚本通过表单发送的文件上传为止。我已经删除了所有可能的额外代码,因此现在已经白手起家,但我仍然无法解决它:

upload.php

<?php

foreach($_FILES['files']['name'] as $f => $name){};

$returnData = array(

        "infoMsg"       => "message for user",
        "color"         => "orange"
    );  
echo json_encode($returnData);
?>

html片段:

<form id="fileUpload" name="fileUpload" enctype="multipart/form-data">

    <input type="file" id="file" name="files[]" multiple="multiple"/>

    </form>

    <button onclick="dSubmit('fileUpload' , 'inc/upload.php')">test</button>

dSubmit是提交表单的功能,一切正常,直到我介绍了上载文件的循环。我收到的错误是:

未捕获到的SyntaxError:JSON中位置0上的意外令牌<< / p>

我看不到多余的字符/空格或其他可能导致JSON问题的东西。

以下是在头部找到的dSubmit代码:

function dSubmit(formName, formAction){
    // formName         = id of Form to process
    // formAction       = php file to parse data to
    var url = formAction;
    event.preventDefault()

    for ( instance in CKEDITOR.instances )
        CKEDITOR.instances[instance].updateElement();

        $.ajax({
               type: "POST",
               url: url,
               data: $("#" + formName).serialize(), 
               success: function(returnData)
               {
                    var data = JSON.parse(returnData);  // Return php array from formAction
                    var passedInfoMsg   = (data['infoMsg']);    // infoMsg (if set)
                    var color           = (data['color']);      // infoMsg color (if set)
                    var resetForm       = (data['reset']);      // boolean reset submitted form upon submission
                    var fileToLoad      = (data['fileToLoad']); // fileToLoad (if set)
                    var divToLoad       = (data['divToLoad']);  // divToLoad fileToLoad in (if set)
                    console.log("Form Return: passedInfoMsg: " + passedInfoMsg + " | color: " + color + " | Reset: " + resetForm + " | fileToLoad: " + fileToLoad + " | divToLoad: " + divToLoad);

                    if(passedInfoMsg!==undefined) {
                        // If message defined, display message
                        infoMsg(passedInfoMsg,color);
                    }
                    if(resetForm===true) {
                        // clear submitted form upon request from formAction
                        clearForm($("#"+formName))
                    }

                    if(fileToLoad!==undefined) {
                        // if fileToLoad is set, run dLoader
                        dLoader(fileToLoad,divToLoad);
                    }
               }
            });

            return false; // avoid to execute the actual submit of the form.
        }

要求的完整代码:

storage.php(进行上传的位置):

<?php

    require $_SERVER['DOCUMENT_ROOT'] . '/../vendor/bucketScripts/start.php';  // include AWS email parser

    $folderTitle = "Client Portal";
    $projectId  = "36";
    $folder     = "client";

$objects = $s3->getIterator('ListObjects', array(
    "Bucket" => "openplanman",
    "Prefix" => "Projects/$projectId/$folder/" //must have the trailing forward slash "/"
));
$passedPrefix = "Projects/$projectId/$folder/";
?>


        <div class="row">
        <div class="12u 12u$(medium)">
        <h3><?php echo $folderTitle;?></h3>
        </div>

    <form id="fileUpload" name="fileUpload" enctype="multipart/form-data" method="POST" action="inc/uploadFiles.php" target="_blank">

        <input type="hidden" name="projectId" value="<?php echo $projectId;?>">
        <input type="hidden" name="uploadFolder" value="<?php echo $folder;?>">
        <input type="hidden" name="folderTitle" value="<?php echo $folderTitle;?>">

        <input type="file" id="file" name="files[]" multiple="multiple"/>
        <input type="submit" value="Upload">
    </form>

    <button onclick="dSubmit('fileUpload' , 'inc/uploadFiles.php')">test</button>


    <div class="12u 12u$(medium)">
    <table>
<?php
$fileArray  = array();
foreach ($objects as $object) {
// Load into a new array    
    array_push($fileArray, $object['Key']); 
}

foreach ($fileArray as $file) {

    $noPrefixFileName = str_replace("$passedPrefix","",$file);
    if($noPrefixFileName!=null)
    {
        $urlFilename = urlencode($noPrefixFileName);

    echo "<tr><td>" . $noPrefixFileName . "</td><td><a onclick=\"fileRequest.php?id=$projectId&folder=$folder&req=$urlFilename\" target='_blank'><i class='fa fa-cloud-download' aria-hidden='true'></a></td><td><i class='fa fa-eye' aria-hidden='true'></td></tr>";
    }

}   
?>
    </table>
</div>
</div>

uploadFiles.php(处理上载的PHP脚本,在POST不能通过AJAX时起作用)

<?php


require $_SERVER['DOCUMENT_ROOT'] . '/../vendor/bucketScripts/start.php';  

$err = 0;


$projectId = $_POST['projectId'];

$uploadFolder       = $_POST['uploadFolder'];


$path =  $_SERVER['DOCUMENT_ROOT'] . '/../tmp/';  // include AWS email parser
$bucketPath = "../../../tmp/";


if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
    // Loop $_FILES to exeicute all files
    foreach ($_FILES['files']['name'] as $f => $name) {     
        if ($_FILES['files']['error'][$f] == 4) {
            continue; // Skip file if any error found
        }          
        if ($_FILES['files']['error'][$f] == 0) {              
         // No error found! Move uploaded files 
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))

        $fileName = $_FILES["files"]["name"][$f];



        //  echo "<br>Key: " . "Projects/$projectId/$uploadFolder/$fileName";
        //  echo "<br>Source: " . "$bucketPath$fileName";

                try {
            $s3->putObject([
                'Bucket'     => $config['s3']['bucket'],
                'Key'        => "Projects/$projectId/$uploadFolder/$fileName",
                'SourceFile' => "$bucketPath$fileName", 
                'ACL'        => 'public-read',
    ]);
} catch (S3Exception $e) {

$err = 1;



            }

unlink($path.$name); // Housekeeping
        }
    }

}

            $returnData = array(

        "infoMsg"       => "user message",
        "color"         => "orange",

    );  



    echo json_encode($returnData);
?>

2 个答案:

答案 0 :(得分:0)

希望有帮助..!
您的文件数组变为:-

$_FILES['files'][0]['name']
$_FILES['files'][1]['name']

当您上传多个文件时。

答案 1 :(得分:0)

您收到此错误,是因为浏览器将一个PHP错误响应视为json内容,而不是。

您可以通过chrome开发人员工具找出错误响应

  • 按F12打开开发人员工具
  • 选择“网络”标签
  • 选择XHR过滤器
  • 选择您提出的请求
  • 在右侧,您可以找到将包含原始响应的响应选项卡

顺便说一句,我认为您的问题是您的代码尝试遍历$ _FILES ['files'] ['name']这是字符串:)