我一直在寻找一种解决方案,当输入字段不在表单标记内时,使用 Ajax 上传文件。我已经尝试过这个solution .
这是我的 HTML
<span id="user-image-up-btn">Last opp bilde</span>
<input id="user_image_upload" type="file" />
这是我的代码,我得到返回TypeError: undefined is not an object (evaluating '$("#user_image_upload").files')
或者当我使用替代数字2时,我获取对象,对象
。
这是我的 jQuery
// IMAGE UPLOAD
$("#user_image_upload").change(function() {
var fileform = new FormData();
fileform.append('pictureFile', $("#user_image_upload").files[0]);
$.ajax({
url: '/userimageupload',
type: 'POST',
processData: false,
contentType: false,
dataType : 'json',
data: fileform,
beforeSend: function(){
$("#user-image-up-btn").html('Laster opp...');
console.log(fileform);
},
success: function(data){
$("#user-image-up-btn").html('Last opp bilde');
console.log(fileform);
},
error: function(exception){
alert('error:'+exception);
console.log(fileform);
}
});
});
编辑:
通过使用 Adeneo 的答案,我成功上传了文件。但是,我仍然收到 error:[object Object]
,这会导致表单的其余部分失败。怎么会这样?
最佳答案
jQuery 对象没有 files
属性,该属性将是底层 DOM 节点
$("#user_image_upload").on('change', function() {
var fileform = new FormData();
fileform.append('pictureFile', this.files[0]);
$.ajax({
url: '/userimageupload',
type: 'POST',
processData: false,
contentType: false,
dataType : 'json',
data: fileform,
beforeSend: function(){
$("#user-image-up-btn").html('Laster opp...');
},
success: function(data){
$("#user-image-up-btn").html('Last opp bilde');
},
error: function(exception){
alert('error:'+exception);
}
});
});
关于php - 无需插件即可在表单外上传 Ajax 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35255369/