weixin_33670786 2016-11-09 21:16 采纳率: 0%
浏览 31

AJAX(原始JS):上传图片

I am new to ajax (and try to avoid frameworks), I tried to check through PHP if any file is set and show true or false, but it didn't worked so I wonder what I did wrong.

This is my code, HTML and JS:

<form class="file-upload" enctype="multipart/form-data" method="post" action="post.php">
    <input type="file" name="fu-obj" id="fu-obj" />
    <div data-file-upload><!-- Output here: "True" Or "False" if file isset --></div>
    <script>
        // "fu" - file upload
        var fu = {
            response: document.querySelector('[data-file-upload]'),
            ele: document.querySelector('[name="fu-obj"]')
        };

        fu['ele'].onblur = function() {
            if(fu['ele'].files.length > 0) {
                ajax.onreadystatechange = function() {
                    if(this.status === 200 && this.readyState === 4) {
                        fu['response'].innerHTML = this.responseText;
                    }
                }
                ajax.open('POST', 'post.php', true);
                ajax.setRequestHeader('Content-type', 'multipart/form-data');
                ajax.send('fu-obj='+fu['ele'].files[0].name);
            }
        }
    </script>
    <!-- If ajax doesn't work -->
    <button type="submit">Manual Upload</button>
</form>
  • the post.php file is really simple and don't do yet any action, only contains an if() statement if(isset($_POST['fu-obj'])) { echo 'True'; } else { echo 'False'; } to check if it works

UPDATE I've replaced $_POST with $_FILES, when I send it manually it works (but not with ajax)

UPDATE 2 - ajax.js:

var ajax;
if(window.XMLHttpRequest) {
    ajax = new XMLHttpRequest();
}
else {
    // Microsoft IE (5,6)
    ajax = new ActiveXObject();
}

How can I solve this issue? Thank you very much!

(Please, don't suggest jQuery solutions, even if it's easier)

  • 写回答

2条回答 默认 最新

  • weixin_33738555 2016-11-09 21:19
    关注
    ajax.setRequestHeader('Content-type', 'multipart/form-data');
    

    You claim you are sending multipart/form-data

    ajax.send('fu-obj='+fu['ele'].files[0].name);
    

    Then you send (possibly invalid because you forgot to use encodeURIComponent) data encoded as application/x-www-form-urlencoded.

    PHP then fails to decode the data because it tries to use the wrong encoding.

    Put the correct content-type in the first line I quoted.


    You could scrap the XHR entirely. Passing a string to the server to see if the string has been set is an expensive operation. You could just as easily do this in plain JS:

    if (fu['ele'].files[0]) { ... }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)