通过表单和XMLHttpRequest

时间:2018-04-25 11:04:01

标签: javascript php

我只需要使用vanilla.js上传文件,不允许使用任何框架。

形式:

<form id="fileUploadForm" action="fileUpload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileToUpload" id="fileToUpload">
</form>

我将按钮放在表单之外,因为它位于HTML中的另一个位置。

<button id="btnUpload">Upload</button>

这是上传脚本。我正在使用FormData来获取表单数据,如this answer中所述。

<script>

document.getElementById("btnUpload").addEventListener("click", function() {
    fileUpload("fileUploadForm");
});

function fileUpload(pFormId) 
{
    debugger;
    var form = document.getElementById(pFormId);
    var formData = new FormData( form );  //returns no data!

    var request = getHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState === 4 && request.status === 200) {
              console.log("Response Received");
              document.getElementById("debug").innerHTML = request.responseText;

        }
    };
    request.open("POST", "fileUpload.php", true);
//    request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    request.setRequestHeader("Content-type","multipart/form-data");
    formData.append("action","test");  //Add additional POST param
    request.send(formData);
}

function getHttpRequest() 
{
    let xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    return xmlhttp;
}
</script>

我正在使用here中的PHP上传脚本。

<?php

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
     echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

我将调试器附加到我的javascript中,发现formData为空且不包含该文件。 enter image description here

这是我从PHP获得的:

enter image description here 抱歉,文件已存在。

enter image description here 对不起,只有JPG,JPEG,PNG&amp;允许使用GIF文件。因此,您的文件未上传。

即使文件 NOT 已经存在且文件格式为jpg。

更新

这是我在开发者控制台网络选项卡中获得的内容:

Request Payload:
------WebKitFormBoundaryKjnjAyPoCQ7MU1x6
Content-Disposition: form-data; name="fileToUpload"; filename="Koala.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryKjnjAyPoCQ7MU1x6--

我感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

只需删除content-type标题,该标题将在使用FormData时由浏览器自动设置。这样,content-type还将包含用于分隔表单数据的表单边界(分隔有效负载数据的------WebKitFormBoundaryKjnjAyPoCQ7MU1x6--之类的东西)。

答案 1 :(得分:0)

我会稍微修改一下代码。

document.getElementById("btnUpload").addEventListener("click", function() {
    fileUpload("fileUploadForm");
});

您正在click绑定活动。我会对此进行修改并将submit事件附加到表单。

闭包会将事件目标作为回调:

document.getElementById("fileUploadForm").addEventListener("submit", function(e) { // <- pay attention to parameter

    e.preventDefault(); // Prevent the default action so we stay on the same page.
    fileUpload(e); // pass the event to your function
});

现在,转到fileUpload功能。

function fileUpload(e) 
{
    debugger;
    var formData = new FormData( e.target );  // pass the event target to FormData which serializes the data    

    var request = getHttpRequest();
        request.onreadystatechange = function() {
            if (request.readyState === 4 && request.status === 200) {
              console.log("Response Received");
              document.getElementById("debug").innerHTML = request.responseText;
        }
    };

    request.open("POST", "fileUpload.php", true);
    request.setRequestHeader("Content-type","multipart/form-data");
    request.send(formData);
}

免责声明:我根本没有对此进行测试,所以不要复制粘贴并期望它能够正常工作!