?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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 Coze智能助手搭建过程中的问题请教
    • ¥15 12864只亮屏 不显示汉字
    • ¥20 三极管1000倍放大电路
    • ¥15 vscode报错如何解决
    • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
    • ¥15 python随机森林对两个excel表格读取,shap报错
    • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
    • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。
    • ¥30 求给定范围的全体素数p的(p-2)/p的连乘积值
    • ¥15 VFP如何使用阿里TTS实现文字转语音?