簡體   English   中英

為什么不能使用AJAX和formData發送文件?

[英]Why can't I send a file using AJAX and formData?

這是我的代碼,我正在嘗試將文件發送到PHP文件,但不能。 在JS中,答案是input_f.files [0][object File] ,但是PHP返回注意:未定義的索引: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); 

嘗試這個

<?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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM