問題描述

我目前有一個 HTML 表單,用户填寫他們想發佈的廣告的詳細信息。我現在想要添加一個 dropzone,用於上傳要銷售的項目的圖像。我發現 dropzone.js 似乎做了大部分我需要的。但是,當查看文檔時,您需要將整個表單的類指定為’dropzone'(而不僅僅是輸入元素) 。這意味着我的整個表單都成為 dropzone 。是否可以在我的表單的一部分中使用 dropzone,即僅將元素指定為類 dropzone,而不是整個表單?

我可以使用單獨的表單,但我希望用户能夠使用一個按鈕提交它。

或者,是否有另一個 Library 可以做到這一點?

非常感謝

最佳解決方案

這是另一種方法:在您的表單中添加一個 div,其名稱為 dropzone,並以編程方式實現 dropzone 。

HTML:

<div id="dZUpload" class="dropzone">
      <div class="dz-default dz-message"></div>
</div>

JQuery 的:

$(document).ready(function () {
    Dropzone.autoDiscover = false;
    $("#dZUpload").dropzone({
        url: "hn_SimpeFileUploader.ashx",
        addRemoveLinks: true,
        success: function (file, response) {
            var imgName = response;
            file.previewElement.classList.add("dz-success");
            console.log("Successfully uploaded :" + imgName);
        },
        error: function (file, response) {
            file.previewElement.classList.add("dz-error");
        }
    });
});

注意:禁用自動發現,否則 Dropzone 將嘗試附加兩次

博客文章:Dropzone js + Asp.net: Easy way to upload Bulk images

次佳解決方案

Enyo’s tutorial 是優秀的。

我發現本教程中的示例腳本適用於嵌入在 dropzone 中的按鈕 (即表單元素) 。如果您希望將按鈕放在表單元素之外,我可以使用點擊事件來完成此操作:

首先,HTML:

<form id="my-awesome-dropzone" action="/upload" class="dropzone">
    <div class="dropzone-previews"></div>
    <div class="fallback"> <!-- this is the fallback if JS isn't working -->
        <input name="file" type="file" multiple />
    </div>

</form>
<button type="submit" id="submit-all" class="btn btn-primary btn-xs">Upload the file</button>

然後,腳本標籤….

Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element

    // The configuration we've talked about above
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 25,
    maxFiles: 25,

    // The setting up of the dropzone
    init: function() {
        var myDropzone = this;

        // Here's the change from enyo's tutorial...

        $("#submit-all").click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            myDropzone.processQueue();
        });
    }
}

第三種解決方案

“dropzone.js” 是用於上傳圖像的最常用庫。如果您想要將”dropzone.js” 作為您表單的一部分,您應該執行以下步驟:

1) 客户端:

HTML:

    <form action="/" enctype="multipart/form-data" method="POST">
        <input type="text" id ="Username" name ="Username" />
        <div class="dropzone" id="my-dropzone" name="mainFileUploader">
            <div class="fallback">
                <input name="file" type="file" multiple />
            </div>
        </div>
    </form>
    <div>
        <button type="submit" id="submit-all"> upload </button>
    </div>

JQuery 的:

    <script>
        Dropzone.options.myDropzone = {
            url: "/Account/Create",
            autoProcessQueue: false,
            uploadMultiple: true,
            parallelUploads: 100,
            maxFiles: 100,
            acceptedFiles: "image/*",

            init: function () {

                var submitButton = document.querySelector("#submit-all");
                var wrapperThis = this;

                submitButton.addEventListener("click", function () {
                    wrapperThis.processQueue();
                });

                this.on("addedfile", function (file) {

                    // Create the remove button
                    var removeButton = Dropzone.createElement("<button class='btn btn-lg dark'>Remove File</button>");

                    // Listen to the click event
                    removeButton.addEventListener("click", function (e) {
                        // Make sure the button click doesn't submit the form:
                        e.preventDefault();
                        e.stopPropagation();

                        // Remove the file preview.
                        wrapperThis.removeFile(file);
                        // If you want to the delete the file on the server as well,
                        // you can do the AJAX request here.
                    });

                    // Add the button to the file preview element.
                    file.previewElement.appendChild(removeButton);
                });

                this.on('sendingmultiple', function (data, xhr, formData) {
                    formData.append("Username", $("#Username").val());
                });
            }
        };
    </script>

2) 服務器端:

ASP.Net MVC

    [HttpPost]
    public ActionResult Create()
    {
        var postedUsername = Request.Form["Username"].ToString();
        foreach (var imageFile in Request.Files)
        {

        }

        return Json(new { status = true, Message = "Account created." });
    }

第四種方案

我有完全相同的問題,發現瓦蘭·辛亞伊的答案是唯一一個解決了原來問題的答案。那個答案可以簡化,所以這裏有一個更簡單的版本。

步驟是:

  1. 創建一個正常的表單 (不要忘記方法和 enctype args,因為這不會被 dropzone 處理) 。

  2. 使用 class="dropzone"(這就是 Dropzone 附加它) 和 id="yourDropzoneName"(用於更改選項) 放在一個 div 裏面。

  3. 設置 Dropzone 的選項,設置要發佈表單和文件的 URL,停用 autoProcessQueue(因此只有在用户按下’submit’ 時才會發生),並允許多次上傳 (如果需要) 。

  4. 將 init 函數設置為使用 Dropzone,而不是單擊提交按鈕時的默認行為。

  5. 仍然在 init 函數中,使用”sendingmultiple” 事件處理程序沿文件發送表單數據。

Voilà!您現在可以使用正常表單 ($ _POST 和 $ _FILES) 檢索數據 (在 upload.php 中會發生這種情況)

HTML

<form action="upload.php" enctype="multipart/form-data" method="POST">
    <input type="text" id ="firstname" name ="firstname" />
    <input type="text" id ="lastname" name ="lastname" />
    <div class="dropzone" id="myDropzone"></div>
    <button type="submit" id="submit-all"> upload </button>
</form>

JS

Dropzone.options.myDropzone= {
    url: 'upload.php',
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 5,
    maxFiles: 5,
    maxFilesize: 1,
    acceptedFiles: 'image/*',
    addRemoveLinks: true,
    init: function() {
        dzClosure = this; // Makes sure that 'this' is understood inside the functions below.

        // for Dropzone to process the queue (instead of default form behavior):
        document.getElementById("submit-all").addEventListener("click", function(e) {
            // Make sure that the form isn't actually being sent.
            e.preventDefault();
            e.stopPropagation();
            dzClosure.processQueue();
        });

        //send all the form data along with the files:
        this.on("sendingmultiple", function(data, xhr, formData) {
            formData.append("firstname", jQuery("#firstname").val());
            formData.append("lastname", jQuery("#lastname").val());
        });
    }
}

第五種方案

除了 sqram 所説,Dropzone 還有一個額外的無證選項,”hiddenInputContainer” 。所有您需要做的是將此選項設置為要添加隱藏文件字段的窗體的選擇器。和瞧! Dropzone 通常添加到身體的”.dz-hidden-input” 文件字段神奇地移動到您的表單中。不改變 Dropzone 的源代碼。

現在,當這個工作將 Dropzone 文件域移動到你的表單中時,該字段沒有名稱。所以你需要添加:

_this.hiddenFileInput.setAttribute("name", "field_name[]");

到這個行後面的 dropzone.js:

_this.hiddenFileInput = document.createElement("input");

圍繞線 547 。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇