我正在尝试将图像发送到服务器,但我总是收到以下错误:
未捕获的TypeError:无法读取未定义的属性“0”
这是我的代码:
的 HTML
<form id="form1">
<input id="image" name="image" type="file"/>
<input id="btnSave" name='btnSave' type="button" value="Save"/>
</form>
的JavaScript
$('#btnSave').click(function() {
var fd = new FormData();
fd.append( 'file', $("#image").files[0] );
$.ajax({
url: 'img.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
},
error: function(data){
alert(data);
}
});
}
我使用与测试此代码相同的图像测试了类似的表单,我也不想使用此代码提交表单。
答案 0 :(得分:1)
jQuery对象没有files
集合。您需要访问基础input
元素,如下所示:
fd.append('file', $("#image")[0].files[0]);
也就是说,我建议将按钮更改为type="submit"
并将处理程序挂钩到submit
的{{1}}事件。然后你可以将form
元素传递给form
构造函数,如下所示:
FormData
<form id="form1">
<input id="image" name="image" type="file"/>
<input id="btnSave" name='btnSave' type="submit" value="Save"/>
</form>