我想用ajax使用this将文件(图像)提交给php。但是我看到的所有教程和参考文件都是通过“onchange”事件将文件分配给变量。
但我希望在用户点击提交时发送此请求。 但它一直给出错误 - “无法读取未定义的属性0”
<html>
<head>
<script type="text/javascript" src="/scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#btn").on('click', function(event) {
event.preventDefault();
var i=new FormData();
var p=$("#img").files[0];//keep getting error here says "cannot read Property 0 of undefined"
i.append('image',p);
$.ajax({
url: 'uploaded.php',
type: 'POST',
dataType: 'formdata',
data: i,
success:function (response){
console.log(response);
}
})
});
});
</script>
</head>
<body>
<form id="submit" type="POST" action="">
<input type="file" id="img" >
<input type="submit" id="btn">
</form>
</body>
</html>
答案 0 :(得分:0)
如果要异步上传文件,则需要使用IFRAME。
对于jquery,存在非常有用的插件AjaxFIleUpload
示例:
-- Use as little as --
$('#one-specific-file').ajaxfileupload({
'action': '/upload.php'
});
-- or as much as --
$('input[type="file"]').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
答案 1 :(得分:0)
您可以添加此
var p = file = $("#img")[0].files[0];
var fileName = file.name;
var fileSize = file.size;
alert("Uploading: "+fileName+" @ "+fileSize+"bytes");
取自此问题link