簡體   English   中英

jQuery 表單插件:ajaxForm() 不適用於文件上傳

[英]jQuery Form Plugin: ajaxForm() not working with file upload

這是我在使用jQuery Form Plugin的 .ajaxForm() 方法時遇到的問題。 為了讓事情盡可能容易理解,我在評論中包含了大部分重要信息,並附有下面的片段。

在 Chrome 和 Firefox 中進行了測試,一旦我 select 上傳一個文件, 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();
}

謝謝!

文件輸入總是有一些安全原因。 所以復制它,將它重新附加到其他 forms 可以擦除值。 我建議您更改頁面標記以在同一位置使用文件輸入,但以其他形式(當然可見)。 如果 position 文件輸入表格很難不包裹在大表格中,請嘗試使用絕對位置。

如果您不考慮舊瀏覽器的兼容性,只需使用新的 HTML5 API。 看到這個答案: Html 5 文件上傳

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM