duanhuiuw12555 2012-11-17 13:47
浏览 556
已采纳

用json上传文件和一些数据

I'm trying to upload a file to the sever. And also some comments from a input form about this data.

Here I sent the data in 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);  

Then I read the data and send the file to the upload folder:

    $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
    );

The output in console of var_damp($data) is:

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)

You can see the data is sent to the php page. But when I check my upload folder. I can find the file I upload. But the size is zero. That means I upload an empty file!!!

Can some one help me to solve this problem? Thank you very much!!

  • 写回答

2条回答 默认 最新

  • dongtuo7364 2012-11-17 15:46
    关注

    You can upload a file with an ajax request using html5

    what you are looking for is sending data & form data aswell (which is to my knowledge not possible in json)

    look for sending data in this article:

    http://www.html5rocks.com/en/tutorials/file/xhr2/

    There is an nice example on that page that illustrates what you're trying to accomplish :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?