【问题标题】:Ajax file upload outside of form without plugins没有插件的 Ajax 文件在表单之外上传
【发布时间】:2016-05-17 06:33:10
【问题描述】:

当输入字段不在表单标签内时,我一直在寻找使用 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 时,我得到 Object, object

这是我的 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],这会导致表单的其余部分失败。怎么会?

【问题讨论】:

  • 你能为此创建一个 sn-p 或 bin 吗?

标签: php jquery ajax input upload


【解决方案1】:

一个 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);
        }
    });
});

【讨论】:

  • 这有效,this 在函数中使用 ID 元素吗? :)
  • 是的,事件处理程序中的this 始终是目标元素,没有 jQuery 包装。
  • 上传工作但由于某种原因我得到以下信息:error:[object Object]
  • 如果您停止使用警报进行调试,并执行console.log('error', exception); 您可以看到控制台中实际出了什么问题,我怀疑是解析错误,即您没有从服务器返回有效的 JSON ,这是您所期望的,因为您添加了 dataType : 'json' 设置
  • 如果我想返回一个HTML代码,我应该将dataType设置为什么?
猜你喜欢
  • 2010-12-16
  • 2011-08-23
  • 1970-01-01
  • 2013-01-28
  • 2013-03-04
  • 2018-06-29
  • 1970-01-01
  • 1970-01-01
  • 2013-01-12
相关资源
最近更新 更多