dongmaomou4117 2016-05-05 12:38
浏览 70

PHP和AJAX FormData无法通信

This is driving me crazy! I can't understand why ajax doesn't send the file to php, is there anyone able to understand? Here's the code:

----- HTML -----

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

----- JS-----

    mmSingFile = (document.getElementById("mmSelectedDoc").files)[0];

    var mmFilesData = new FormData();

    mmFilesData.append("selectedFiles[]", mmSingFile, encodeURIComponent(mmSingFile.name));

    var x=new XMLHttpRequest();
    x.onreadystatechange = function(e){
        if (x.readyState==4 && x.status==200){
           console.log(x.responseText);
        }
    }
    log(mmFilesData.get("selectedFiles[]"));
    x.open("POST","uploader.php", true);
    x.setRequestHeader("Content-type", "multipart/form-data");
    x.send(mmFilesData);

----- PHP -----

var_dump($_GET);
var_dump($_POST);
var_dump($_FILES);
die();

when i log mmFilesData.get(...) before sending, I can see there's a file inside, but as log on onreadystatechange=4 There are only empty arrays. If I change the content-type to application/x-www-form-urlencoded i get from the post var_dump a result like this:

  ["-----------------------------172450022319283172571100694258

Content-Disposition:_form-data;_name"]=>
  string(813) ""selectedFiles[]"; filename="10434360_995996657086820_5574771356675124169_n.jpg"

Content-Type: image/jpeg

��here's in ascii the file content��

What's happening??? Thank you all!

  • 写回答

1条回答 默认 最新

  • dtnwm4807 2016-05-05 12:43
    关注

    Don't set a content type on your xhr object when sending a formdata object.
    Don't uri encode the filename in the append function.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看