我正在尝试使用Ajax和formData对象将文件发送到服务器。但是我一直得到一个“input.files [0]未定义”想知道你是否可以指出我出错的地方。
// HTML
<!--uploading new media-->
<div class="uploadBtns uploadClass">
<input type="file" id="uploadBtn" class="uploadClass" name="usersUpload" />
<input type="text" id="uploadFile" class="uploadClass" />
<span id="uploadBtnText" class="uploadClass">Browse Media...</span>
<div id="uploadSubmitBtn" class="uploadClass" name="usersUploadSubmit" value="Upload Media">
<span id="submitBtnText" class="uploadClass">Upload Media</span>
</div>
</div>
然后是javascript:
//send pictures via ajax
$("#uploadSubmitBtn").click(function(){
var formData = new FormData();
var inputFile=$("#uploadBtn");
//append the actual file that was selected
formData.append('usersUpload', inputFile.files[0]);
$.ajax({
url : "upload",
type : 'post',
data : formData,
async : true,
processData: false, // tell jQuery not to process the data
contentType: 'multipart/form-data', // tell jQuery not to set contentType
error : function(request){
alert(request.responseText);
},
success : function(resp){
alert("got back " + resp);
}
});
});//end of submitting media
答案 0 :(得分:1)
试试这个
var formData = new FormData($("#formname")[0]);
我不知道你的表格被调用了什么,所以用你的表格名称替换formname,实际上在第二个视图中你没有表格,所以在你的输入周围放一个表格
在你的ajax请求中设置这些:
async: false,
cache: false,
contentType: false,
processData: false
答案 1 :(得分:0)
您已经在使用jQuery了。最好使用Malsup的jquery.form.js
。
Check this link for plugin and usage.也适用于文件上传。
示例:
$('#myForm').ajaxForm( {
beforeSubmit: function(){
},
success : function(){
}
});
答案 2 :(得分:0)
<!--uploading new media-->
<form enctype="multipart/form-data" id="uploadForm">
<div class="uploadBtns uploadClass">
<input type="file" id="uploadBtn" class="uploadClass" name="usersUpload" />
<input type="text" id="uploadFile" class="uploadClass" />
<span id="uploadBtnText" class="uploadClass">Browse Media...</span>
<div id="uploadSubmitBtn" class="uploadClass" name="usersUploadSubmit" value="Upload Media">
<span id="submitBtnText" class="uploadClass">Upload Media</span>
</div>
</div>
</form>
对我来说效果更好,因为我也会做一些多文件上传。 再次感谢
//capture and send file uploads via ajax
$("#uploadSubmitBtn").click(function(){
var formData = new FormData($("#uploadForm")[0]);
var usersFiles=$("#uploadBtn").get(0).files;
//append the actual file that was selected
formData.append('usersUpload', usersFiles);