【发布时间】:2016-03-24 13:11:49
【问题描述】:
我正在使用 Ajax,PHP。
我想在不点击提交按钮的情况下上传图片,我正在使用此答案中描述的方法:How to upload file using jquery ajax and php (without clicking any submit button)
但它不起作用。我是否需要更改数据类型或其他内容?
这是我的代码:
jQuery/Ajax
$(document).ready(function(){
var b = new FormData($(this).closest("form")[0]);
b.append('image', $('input[type=file]')[0].files[0]);
$("#imgInput").change(function(){
$.ajax({
url: "test.php",
type: "post",
datatype: 'json',
processData: false,
contentType: false,
data: b,
success: function(text){
if(text== "success"){
alert("Image uploaded");
}
},
error: function(){
alert("Not uploaded");
}
});
});
});
test.php
<?php
$filename=$_FILES["image"]["name"];
$filetmp=$_FILES["image"]["tmp_name"];
$filetype=$_FILES["image"]["type"];
$filepath="images/".$filename;
move_uploaded_file($filetmp, $filepath);
?>
HTML
<form name="form1" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><input type="text" name="name" placeholder="Enter your name" /></td>
<td rowspan="3"><div class="propic"><img id="" /></div>
<input id="imgInput" type="file" name="image" /></td>
</tr>
<tr>
<td><input type="text" name="username" placeholder="Enter username"/></td>
</tr>
<tr>
<td><input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no."/></td>
</tr>
<tr>
<td><input type="password" name="password" maxlength="12" placeholder="Enter password"/></td>
<td><input id="button" type="submit" name="submit" value="Sign Up" /></td>
</tr>
</table>
</form>
【问题讨论】:
-
你需要调试你的脚本。在
test.php中输入var_dump($_FILES)并检查该请求,例如在 chrome 控制台中。 -
您需要使用
FormData()。 -
我在哪里以及如何使用它@PraveenKumar
-
是什么让你认为
move_uploaded_file是罪魁祸首?