我看到了一些简单的代码,用于使用formdata通过ajax上传图像,但在php端,它在$_POST
内显示为NULL,我尝试echo $_POST['file']['name']
但它没有回复......
我的php文件有:
var_dump($_POST);
如何使用ajax发送的formData到php(在php中)?
$(document).on('change','#image',function(){
var fd = new FormData();
fd.append( 'file', $(this).prop("files")[0]);
console.log(fd);
$.ajax({
type: 'post',
processData: false,
contentType: false,
url: './images.php',
data: fd,
success: function(a){
console.log(a);
}
});
});
#image{display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<label for="image"><i class="fa fa-camera" aria-hidden="true"></i></label><input type="file" name="file" id="image">
答案 0 :(得分:1)
您必须使用超级全球$_FILES
代替$_POST
尝试:
var_dump($_FILES);
输出类似:
array (size=1) 'file' =>
array (size=5)
'name' => string '49e9c80947764261bbd9d46a8063c3d1.jpg' (length=36)
'type' => string 'image/jpeg' (length=10)
'tmp_name' => string 'C:\xampp\tmp\php64A9.tmp' (length=24)
'error' => int 0
'size' => int 3090
答案 1 :(得分:0)
这对我有用。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<form id="imageUpload">
<label for="image"><i class="fa fa-camera" aria-hidden="true"></i></label><input type="file" name="file" id="image">
</form>
<script type="text/javascript">
$(document).on('change','#image',function(){
var fd = new FormData($("#imageUpload")[0]);
fd.append('file',$(this)[0].files[0]);
console.log(fd);
$.ajax({
type: 'post',
processData: false,
contentType: false,
url: 'testimage.php',//change to yours
data: fd,
success: function(a){
console.log(a);
}
});
});
</script>
然后我的PHP
<?php
var_dump($_FILES);
结果: