1

SyntaxError: Unexpected token {当我上传多个文件时,我有一个。而当我只上传一个文件时,它可以工作。

PHP

$uploaddir = 'uploads/';

$arr = array();
foreach ($_FILES["uploadfile"]["error"] as $key => $error) {

  if ($error == UPLOAD_ERR_OK) {
     $file = $uploaddir . basename($_FILES['uploadfile']['name'][$key]);

     if (move_uploaded_file($_FILES['uploadfile']['tmp_name'][$key], $file)) {
         $arr['title'] = $_FILES['uploadfile']['name'][$key];
         $arr['url'] = $file;
         $arr['size'] = $_FILES['uploadfile']['size'][$key];
     }
     echo json_encode($arr);
  }
}

查询

 onComplete: function(file, response){
     response = JSON.parse(response);
     console.log('data = '+response.title);
     console.log('data = '+response.url);
     console.log('data = '+response.size);
 }

新的 VAR DUMP PHP(带有@hek2mgl 代码)

array(2) {
[0]=>
    array(3) {
        ["title"]=> string(27) "facebook-icon-east-west.jpg"
        ["url"]=> string(35) "uploads/facebook-icon-east-west.jpg"
        ["size"]=> int(35227)
    }
[1]=>
    array(3) {
        ["title"]=> string(25) "facebook-graph-search.jpg"
        ["url"]=> string(33) "uploads/facebook-graph-search.jpg"
        ["size"]=> int(53122)
    }
}
4

1 回答 1

2

上传多个文件后,您在哪里输出多个 json 文档。您必须将这些多个节点包装到一个数组元素中。

你做了:

{
   "title" : "dsfsd"
   ...
}
{<--- Syntax error
   "title" : "dsfsd"
   ...
}

你必须这样做:

[{
   "title" : "dsfsd"
   ...
},
{
   "title" : "dsfsd"
   ...
}]

下面是正确的 PHP 代码:

$uploaddir = 'uploads/';

$files = array();
foreach ($_FILES["uploadfile"]["error"] as $key => $error) {
  if ($error == UPLOAD_ERR_OK) {
     $path = $uploaddir . basename($_FILES['uploadfile']['name'][$key]);

     if (move_uploaded_file($_FILES['uploadfile']['tmp_name'][$key], $path)) {
         $files [] = array (
            'title' => $_FILES['uploadfile']['name'][$key],
            'url' => $path,
            'size' => $_FILES['uploadfile']['size'][$key]
         );
     }
  }
}

echo json_encode($files);
于 2013-01-18T10:47:14.847 回答