FormData追加不起作用 [英] FormData append not working
问题描述
我用HTML中的 input
元素编写了一个图像上传到我的本地Apache网络服务器。 文件
被记录为非空,但为什么 form_data
完全为空?
I wrote this to upload an image to my local Apache webserver using input
element in HTML. The file
is logged as not empty, but why is the form_data
completely empty?
$('#upload-image').change(function(e){
var file = e.target.files[0];
var imageType = /image.*/;
if (!file.type.match(imageType))
return;
console.log(file);
var form_data = new FormData();
form_data.append('file', file);
console.log(form_data);
$.ajax({
url: 'http://localhost/upload.php',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
这是我本地的 upload.php
web服务器
This is my upload.php
on local webserver
<?php
header('Access-Control-Allow-Origin: *');
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . $_FILES['file']['name'];
echo $target_path;
}
?>
echo
The console.log(response)
logs all the code lines of PHP file, instead of the returned result of echo
推荐答案
当使用 console.log(formData)
记录formData对象时,它总是返回空白,因为您无法记录formData。
When logging a formData object with just console.log(formData)
it always returns empty, as you can't log formData.
如果您在发送之前只需要记录它,就可以使用 entries()
获取formData对象中的条目
If you just have to log it before sending it, you can use entries()
to get the entries in the formData object
$('#upload-image').change(function(e) {
var file = e.target.files[0];
var imageType = /image.*/;
if (!file.type.match(imageType)) return;
var form_data = new FormData();
form_data.append('file', file);
for (var key of form_data.entries()) {
console.log(key[0] + ', ' + key[1]);
}
$.ajax({
url: 'http://localhost/upload.php',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
这篇关于FormData追加不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!