警告:在第0行的Unknown中,multipart / form-data POST数据中缺少边界

时间:2014-12-24 10:55:04

标签: javascript php ajax html5 xmlhttprequest

我正在处理文件上传器,当输入被更改时上传图像我的代码为html格式

<form method="post" enctype="multipart/form-data">
     <input name="uploaded[]" type="file" id="file_upload"/>
</form>

我的JavaScript和Ajax:

        document.getElementById("file_upload").onchange = function() {
            var id = document.getElementById("user_id").innerHTML;
            var file = document.getElementById("file_upload").files[0];
            alert(file.size);
            var formdata = new FormData();
            formdata.append("filer",file,true);
            var ajax = new XMLHttpRequest();
            ajax.onreadystatechange =
            function(){
                if(ajax.readyState==4 && ajax.status==200){
                    document.getElementById("one").remove();
                    var img = document.createElement('img');
                    var first_path = '/user_image/';
                    var path = first_path.concat(id,'.png');
                    img.setAttribute('alt','User image');
                    img.setAttribute('id','one');                        
                    img.setAttribute('src',path);
                    document.getElementById("user").appendChild(img);  
                    alert("end");
                }    
                else{
                    document.getElementById("one").remove();
                    var img = document.createElement('img');
                    img.setAttribute('src','/img/loading.gif');
                    img.setAttribute('alt','User image');
                    img.setAttribute('id','one');
                    document.getElementById("user").appendChild(img);                        
                }
            }               
            ajax.open("POST","upload_image.php");
            ajax.setRequestHeader("Content-Type", "multipart/form-data");
            ajax.send(formdata);
        };

我的PHP代码很简单就是测试一切是否正常

require("../includes/config.php"); //config folder to start the session
if($_SERVER["REQUEST_METHOD"]=="POST"){
       echo '<pre>',print_r($_FILES),'</pre>'; //dumping some variable and arrays to see where the problem is 
}

我从服务器获得的请求是警告:在第0行的Unpart中的multipart / form-data POST数据中缺少边界但我发送了formdata和请求标头,我打开了文件。

2 个答案:

答案 0 :(得分:14)

您必须删除以下行:

ajax.setRequestHeader("Content-Type", "multipart/form-data");

答案 1 :(得分:-2)

而不是将数据作为multipart/form-data发送:

ajax.setRequestHeader("Content-Type", "multipart/form-data");

您应该将其发送为application/json

ajax.setRequestHeader("Content-Type", "application/json");