jQuery Form Plugin:ajaxForm()不使用文件上传

时间:2011-07-21 05:26:48

标签: javascript jquery jquery-plugins

这是我在使用jQuery Form Plugin的.ajaxForm()方法时遇到的问题。为了让事情尽可能理解,我在下面的片段中将大部分显着信息都包含在评论中。

在Chrome和Firefox中都进行了测试,一旦我选择要上传的文件, FORM_2 确实会发布到服务器。问题是帖子中没有包含deal_upload_image_file输入,因此服务器没有收到任何文件。

HTML:

<!-- FORM_1: Big form, I need to position a file input field in here, -->
<!-- but don't want to submit the file with this form                 -->
<form id="edit_deal_form">
  <div id="upload_image_div">
    <!-- Javascript appends the "deal_upload_image_file" input here, then -->
    <!-- appends it to FORM_2 when a file is selected                     -->
  </div>
</form>

<!-- FORM_2: A second form that is not visible to user and will -->
<!-- actually do the post of the  multipart data                -->
<form id="deal_upload_image_form" name="upload_image_form" method="post" enctype="multipart/form-data" action="/upload_image" accept-charset="UTF-8">
</form>

的javascript:

$(function() {
  add_upload_image_elements();
});

// Add deal_upload_image_file input to FORM_1, and add onChange handler
// to immediately POST to server once a file has been selected
function add_upload_image_elements() {
    $('<input>').attr("id", "deal_upload_image_file").attr("name", "deal_upload_image_file").attr("type", "file").appendTo($('#upload_image_div'));
    $('#deal_upload_image_file').change(function () {
        upload_image();
        return false;
    });
}

// Move the file input to FORM_2, set up the ajaxForm handler,
// and call submit() on FORM_2.
//
// For clean up, clear the file input field and add it back to FORM_1.
function upload_image() {
    // This input field is not getting posted with FORM_2
    // even though I append it here!!!
    $('#deal_upload_image_file').appendTo($('#deal_upload_image_form'));

    $('#deal_upload_image_form').ajaxForm({
        success: function(response) {
            alert("Success callback");
        },
        error: function(response) {
            alert("Error callback");
        }
    });
    $('#deal_upload_image_form').submit();

    // clean up
    $('#deal_upload_image_file').remove();
    add_upload_image_elements();
}

谢谢!

2 个答案:

答案 0 :(得分:0)

文件输入总是有一些安全原因。因此复制它,将其重新连接到其他形式可以擦除值。我建议你改变页面标记以在同一个地方使用文件输入,但是以其他形式(当然可见)。如果在没有以大格式包装的情况下很难定位文件输入表单,请尝试使用绝对位置。

答案 1 :(得分:0)

如果您不考虑旧的浏览器兼容性,请使用新的HTML5 API。请参阅此答案:Html 5 File upload