[英]Upload files with Ajax and Jquery
在過去的幾個小時里,我一直試圖弄清楚如何通過ajax上傳文件,但一無所獲。
代碼如下:HTML:
<form action="" method="post" id="uploadForm" enctype="multipart/form-data">
<input type="file" name="image" id="image">
<input type="submit">
</form>
JS:
<script>
jQuery(document).ready(function(){
jQuery('form#uploadForm').on('submit', function(e){
e.preventDefault();
var file = jQuery('#image')[0].files[0];
var form_data = new FormData( jQuery("form#uploadForm")[0] );
form_data.append( 'image', file );
jQuery.ajax({
url: 'index.php?a=do',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: form_data,
success: function(response) {
console.log(response);
},
});
return false;
});
});
</script>
PHP:
<?php
$a = isset($_GET['a']) ? $_GET['a'] : '';
if($a <> '') {
echo "result - ";
var_dump($_POST);
die();
}
?>
結果,我得到一個空數組,但是如果我將文件字段保留為空,則得到:
result - array(1) {
["image"]=>
string(9) "undefined"
}
我試過serialize(),serializeObject(),serializeArray(),$。param,每次該死的控制台中出現“未定義函數”錯誤。
我在stackoverflow上遇到了許多類似的問題,但沒有任何幫助。 我嘗試用$ .post代替$ .ajax,並且包含form_data的“數據”字段為空。
我需要一個Wordpress插件,而我試圖避免在上傳部分使用第三方的JS插件。
$_FILES
是您檢查上傳文件的地方,而不是$_POST
。
同樣,在您的代碼中,您實際上以實例化表單數據對象的形式上載了兩次文件,然后再次通過添加將其添加。 要么做
var form_data = new FormData( jQuery("form#uploadForm")[0] );
要么
var form_data = new FormData();
form_data.append( 'image', file );
<html>
<head>
<title>Ajax file upload</title>
<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: "ajax_php_file.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(data);
}
});
}));
</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.