FormData对象,似​​乎没有上传我的文件......

时间:2015-09-07 15:12:37

标签: javascript php

我跟随this guide使用aJax上传图片,主要是因为我可以有一个进度条。但由于某种原因,PHP脚本似乎没有收到文件!

这是我的JavaScript:

function submitFile() {
    var form = document.forms.namedItem("imageUpload");
    var formData = new FormData(form);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "php/uploadImage.php", true);
    xhr.onload = function(e) {
        if (xhr.status == 200) {
            console.log("uploaded!");
            doc("imageResponse").innerHTML = xhr.responseText;
        } else {
            console.log("error!");
            doc("imageResponse").innerHTML += "Error " + xhr.status + " occurred when trying to upload your file.<br \/>";
        }
    };

    //Progress
    /*
    xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
            var currentPercentage = Math.round(e.loaded / e.total * 100);
            document.getElementById("imageUpload").innerHTML = "UPLOAD IMAGE " + currentPercentage + "%";
            document.getElementById("imageUpload").style.backgroundSize = currentPercentage + "% 100%";
        }
    };
    */

    //Send data
    xhr.send(formData);
}

这是我的PHP文件,它接收文件:

<?php
session_start();
print_r($_FILES);
?>

目前PHP文件正在返回一个空数组......它应该有我的文件!

  

Array()

1 个答案:

答案 0 :(得分:0)

我设法修复了我的代码,这是任何有相同问题的人的工作版本。我决定使用JavaScript创建一个新表单,并将文件字段值附加到这个新表单。

我这样做主要是因为我的情况。

function submitFile(file,buttonId) {
    //Generate a new form
    var f = document.createElement("form");
    f.setAttribute("method", "POST");
    f.setAttribute("enctype", "multipart/form-data");

    //Create FormData Object
    var formData = new FormData(f);

    //Append file
    formData.append("image", file.files[0], "image.jpg");

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "php/uploadImage.php", true);
    xhr.onload = function(e) {
        if (xhr.status == 200) {
            document.getElementById(buttonId).innerHTML = "UPLOAD COMPLETE";
            //console.log("uploaded!");
        } else {
            //console.log("error!");
            alert("Error " + xhr.status + " occurred when trying to upload your file");
        }
    };

    //Progress
    xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
            var currentPercentage = Math.round(e.loaded / e.total * 100)-1;
            document.getElementById(buttonId).innerHTML = "UPLOAD IMAGE " + currentPercentage + "%";
            document.getElementById(buttonId).style.backgroundSize = (currentPercentage+1) + "% 100%";
            if (currentPercentage==99) {
                document.getElementById(buttonId).innerHTML = "Processing image";
            }
        }
    };

    //Send data
    xhr.send(formData);
}