使用Ajax传递图像

时间:2019-01-01 08:25:52

标签: javascript php ajax ajaxform

用于上传图片的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个标头请求。

首先:未设置数据。

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

第二:未设置数据。

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

第三:返回此[对象FormData]。

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

我也尝试过没有头请求,也没有设置数据。

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

请不要使用JQuery。

2 个答案:

答案 0 :(得分:1)

您在此字符串中遇到的问题:

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

答案 1 :(得分:1)

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

  

带有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>
  

使用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);
}
?>