我正在尝试将文件上载到服务器。以及输入表单中有关此数据的一些注释。
在这里我用js发送了数据:

var postContainer = new Array();
        postContainer.push(
        {
            file : file,
            f_name : file.name,
            input1 : it1Value
        });

        var newJ = JSON.stringify(postContainer);
        xhr.setRequestHeader("X-File-Name", file.name);
        var resText;
        xhr.setRequestHeader("Content-type","application/json");
        xhr.onreadystatechange = function(){
            if(xhr.readyState != 4){
                return;
            }
            console.log(xhr.responseText);
        }
        xhr.send(newJ);

然后我读取数据并将文件发送到上载文件夹:
    $data = file_get_contents("php://input");
    $data = json_decode($data);
    var_dump($data);
    $this->fileName = $data[0]->{"f_name"};
    $this->genre = $data[0]->{"input1"};
    $this->file = $data[0]->{"file"};
            file_put_contents(
    $this->path . $this->fileName,
    $this->file
    );

var_damp($data)的控制台输出为:
array
0 =>
object(stdClass)[2]
  public 'file' =>
    object(stdClass)[3]
      public 'webkitRelativePath' => string '' (length=0)
      public 'lastModifiedDate' => string '2012-06-26T06:25:34.000Z' (length=24)
      public 'name' => string 'Belgium.png' (length=11)
      public 'type' => string 'image/png' (length=9)
      public 'size' => int 28228
  public 'f_name' => string 'Belgium.png' (length=11)
  public 'input1' => string 'Genre' (length=5)

您可以看到数据被发送到php页面。但当我检查我的上传文件夹时。我可以找到我上传的文件。但尺寸是零。这意味着我上传了一个空文件!!!
有人能帮我解决这个问题吗?
非常感谢你!啊!

最佳答案

您可以使用html5上传带有ajax请求的文件
您需要的是发送数据和表单数据(据我所知,这在json中是不可能的)
在本文中查找发送数据:
http://www.html5rocks.com/en/tutorials/file/xhr2/
在那一页上有一个很好的例子说明了你想要完成的任务:)

10-08 09:08
查看更多