?Briella 2014-08-21 23:06 采纳率: 0%
浏览 165

Ajax POST文件上传

I have what i thought was a very simple task, but I can't seem to get it working correctly. I'm hoping someone with a better understanding of Ajax can help me figure out where i'm going wrong.

I have a simple input box on my page...

<form onchange="imgUpload();" >
    File: <input id='img' name="myfile" type="file" />
</form>

Here is the function it calls...

function imgUpload(){


    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            // document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
            alert(xmlhttp.responseText);
        }
    }

    var imgFile = document.getElementById("img");
    var formData = new FormData();                  // Create a FormData instance
    formData.append("upload", imgFile.files[0]);        //Add the file

    xmlhttp.open("POST","img_upload.php",true);
    xmlhttp.setRequestHeader("Content-type","multipart/form-data");
    xmlhttp.send(formData);     
}

My PHP page to process the POST currently does nothing more then echo back the array of the post...

<?php
    print_r($_POST);
    exit;
?>

My problem is when I get the result of the POST back, it's an empty array. Apparently I'm not actually sending the file to my processing page. Any insight on where i've gone wrong would be greatly appreciated.

I have found several other posts on this forum and others that talk about the same issue or topic, but they don't seem to get me where I need to be.

Thanks in advance!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 求三轴之间相互配合画圆以及直线的算法
    • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
    • ¥15 名为“Product”的列已属于此 DataTable
    • ¥15 安卓adb backup备份应用数据失败
    • ¥15 eclipse运行项目时遇到的问题
    • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
    • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
    • ¥15 自己瞎改改,结果现在又运行不了了
    • ¥15 链式存储应该如何解决
    • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站