使用 Ajax 传递图像

Passing an Image with Ajax

HTML 上传图片的表单:

<form method="post" enctype="multipart/form-data">
<div>
<input type="file" id="image">
<button type="button" class="ImgSubmitButton" onclick="uploadImages();">UPLOAD IMAGE</button>
</div>
</form>

Javascript/Ajax 用于发送数据。

var RequestObject = false;
if (window.XMLHttpRequest) {
    RequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
    RequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}

function uploadImages() {
    if (RequestObject) {
        var formData = new FormData();
        var myfile = document.getElementById('image').files[0];
        formData.append('file', myfile);
        RequestObject.open("POST", "processFileA.php");

        RequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        RequestObject.onreadystatechange = function() {
            if (RequestObject.readyState == 4 && RequestObject.status == 200) {
                document.getElementById('err').innerHTML = RequestObject.responseText;
            }
        }
        RequestObject.send("data=" + formData);
    }
    return false;
}

PHP很简单,就是检查数据是否设置好了。

if(isset($_POST['data'])){ 
echo $_POST['data'];
echo "data is set";
} else {
echo "data is not set";
}

我检查了 3 个 header 请求。

第一:数据未设置

RequestObject.setRequestHeader('Content-Type','multipart/form-data');

其二:数据未设置

RequestObject.setRequestHeader('Content-Type', "multipart/form-data; charset=utf-8; boundary=" + Math.random().toString().substr(2));

第三个:returns 这个 [object FormData]。

RequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

我也试过没有 header 请求,但数据未设置。

我知道如何通过使用 PHP 提交的常规表单安全地处理表单,但不确定如何处理通过 Ajax 传递的 [object FormData]。如果他们是更好的方法或我做错了什么,请告诉我。我的问题是如何通过 Ajax 正确发送图像文件来处理它,就像您以常规形式提交以在 PHP.

中正确处理它一样

请不要JQuery.

你在这个字符串中的问题:

RequestObject.send("data=" + formData);

当您尝试 String + formData 时,您进行了串联,并且 formData 转换为 String,正如我们所知 formData 它是对象。

这是发送数据的正确方法:

RequestObject.send(formData);

只需像本示例中那样发送数据:https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript

您可以通过 ajax 使用不同的方式,请参见下面的示例:

THIS ANSWER WITH JUST JAVASCRIPT AJAX

<html>
<head>

<script >
function uploadImages(){
var xhr = new XMLHttpRequest();
var url = "processFileA.php";
xhr.open("POST", url, true);
//xhr.setRequestHeader("Content-Type", "application/json");
//xhr.setRequestHeader("accept", "application/json, text/plain, */*");

xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var content= xhr.responseText;

    console.log(content);



    }
};

var datae=document.getElementById('uploadimage');
var data = new FormData(datae);
xhr.send(data);
}


</script>
</head>
<body>
<form id="uploadimage" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" id="image">
<button type="button" class="ImgSubmitButton" onclick="uploadImages();">UPLOAD IMAGE</button>
</div>
</form>
</body>
</html>

THIS ANSWER USING JQUERY AJAX

<link href='http://fonts.googleapis.com/css?family=Roboto+Condensed|Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script >
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "processFileA.php", // Url to which the request is send
type: "POST",             // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false,       // The content type used when sending data to the server.
cache: false,             // To unable request pages to be cached
processData:false,        // To send DOMDocument or non processed data file it is set to false
success: function(data)   // A function to be called if request succeeds
{
alert('done')

}
});
}));



});

</script>
</head>
<body>
<form id="uploadimage" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" id="image">
<button type="submit" class="ImgSubmitButton" >UPLOAD 
            IMAGE</button>
</div>
</form>
</body>
</html>

PHP 文件:processFileA.php

<?php

if(isset($_FILES["file"]["type"]))
{
$file=(file_get_contents($_FILES["file"]['tmp_name']));
file_put_contents('tmp_name.'.str_replace('image/','',$_FILES["file"]["type"]),$file);
}
?>