首页 > 解决方案 > 为什么我不能使用 AJAX 和 formData 发送文件?

问题描述

这是我的代码,我正在尝试将文件发送到 PHP 文件,但我不能。在 JS 中,答案是input_f.files[0]是一个[object File],但是 PHP 返回Notice: Undefined index: file...,我认为 formData 不起作用。

PHP 代码

<?php
$file = $_FILES['file']['size'];
echo $file;

JS代码

var text = document.getElementById('text');
var input_f = document.getElementById('input_f');//Input file

var xmlhttp = new XMLHttpRequest();
var formData = new FormData();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        text.innerHTML = this.response;
    }
};
xmlhttp.open("POST","php/convert.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
formData.append('file', input_f.files[0]);
xmlhttp.send(formData);

标签: javascriptphpajaxfile-upload

解决方案


尝试这个

<?php
    $file = $_FILES['file']['size'];
    echo $file;
    JS Code

    var text = document.getElementById('text');
    var input_f = document.getElementById('input_f');//Input file

    var xmlhttp = new XMLHttpRequest();
    var formData = new FormData();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            text.innerHTML = this.response;
        }
    };
    xmlhttp.open("POST","php/convert.php");
    formData.append('file', input_f.files[0]);
    xmlhttp.send(formData);

推荐阅读