首页 > 解决方案 > 如何让 Dropzone.js 结合多个输入和选择字段工作

问题描述

我试图让dropzone.js使用多个输入并选择字段工作。

还阅读了 dropzone.js 文档,我看到 dropzone 表单看起来像一个独立的表单。因此,当我尝试在 dropzone 表单中添加更多输入和选择字段时,整个表单都会被 dropzone 覆盖,而我只希望其中一部分成为 dropzone。我还发现我可以通过阅读其他 stackoverflow 文章来修复它。

我所做的是我创建了一个包含3 个输入字段7 个选择选项和 + 1 个 dropzone的表单,并且我有 1 个提交按钮,应该将它们一起提交。

我已经关注了这篇 stackoverflow 文章:将 Dropzone.js 集成到现有的 HTML 表单和其他字段中

问题:当我提交表单时,文件开始上传(进度动画显示),但文件没有上传到服务器,表单没有完全提交,字段值也没有发送到数据库。

这是表单开始代码:

<form  id="drform" name="formapdf2" method="post" action="dodaj-save.php" autocomplete="off" enctype="multipart/form-data">

这是提交按钮代码:

<button id="sbmtbutton" class="btn btn-primary" name="insert" type="submit">Registruj radnika</button>

这是我使用的 JS 代码:

Dropzone.options.dropfile = {
    acceptedFiles: 'image/*',
    maxFiles: 1,
    resizeWidth: 300,
    resizeHeight: 300,
    resizeMethod: 'contain',
    resizeQuality: 1.0,
    maxFilesize: 4,
    autoProcessQueue: false,
    url: 'dodaj-save.php',
    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("sbmtbutton").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("name", jQuery("#dzfname").val());
            formData.append("qrcode", jQuery("#dzfqrcode").val());
            formData.append("company", jQuery("#select_id").val());
            formData.append("money", jQuery("#dzfmoney").val());
            formData.append("checkin", jQuery("#dzfcheckin").val());
            formData.append("checkout", jQuery("#dzfcheckout").val());
            formData.append("checkin1", jQuery("#dzfcheckin1").val());
            formData.append("checkout1", jQuery("#dzfcheckout1").val());
            formData.append("checkin2", jQuery("#dzfcheckin2").val());
            formData.append("checkout2", jQuery("#dzfcheckout2").val());
        });
    }
}

我也有用于上传的 PHP 代码,但我不确定 php 代码是否是问题所在,我是否也应该在这里显示此代码。如果您需要其他任何东西来确定问题所在,请告诉我。我希望我没有违反任何 stackoverflow 规则,因为这是我的第一篇文章。

标签: javascriptphpjqueryhtml

解决方案


尝试这个。它与您的操作方式略有不同,但效果非常好。

您可以做的第一件事是通过在您的外部添加以下内容来阻止 Dropzone.js 自动检测表单标签$(document).ready(function(){})

Dropzone.autoDiscover = false;

然后使用 AJAX 函数创建 Dropzone 实例。在按钮点击事件内部$(document).ready(function(){})但在按钮外部执行此操作:

let myDropzone = new Dropzone('.dropzone', { //Give your input (or form if you're not sending anything else) a class of dropzone
    autoProcessQueue: false,
    acceptedFiles: ".svg", // Add accepted file types here
    url: "dodaj-save.php", // Your PHP file here
    init: function() {
        this.on("addedfile", function() {
            //Do something before the file gets processed.
        })
        this.on("sending", function(file, xhr, formData){
            //Do something when the file gets processed.
            //This is a good time to append additional information to the formData. It's where I add tags to make the image searchable.
            formData.append('tags', 'cat-cats-kittens-meow')
        }),
        this.on("success", function(file, xhr) {
            //Do something after the file has been successfully processed e.g. remove classes and make things go back to normal. 
        }),
        this.on("complete", function() {
            //Do something after the file has been both successfully or unsuccessfully processed.
            //This is where I remove all attached files from the input, otherwise they get processed again next time if you havent refreshed the page.
            myDropzone.removeAllFiles();   
        }),
        this.on("error", function(file, errorMessage, xhr) {
            //Do something if there is an error.
            //This is where I like to alert to the user what the error was and reload the page after. 
            alert(errorMessage);
            window.location.reload();
        })
    }
});

然后循环遍历所有附加文件并在单击提交按钮时连续处理所有文件:

const uploadBtn = document.querySelector('#sbmtbutton');
uploadBtn.addEventListener('click', () => {
    const acceptedFiles = myDropzone.getAcceptedFiles();
    for (let i = 0; i < acceptedFiles.length; i++) {
        myDropzone.processFile(acceptedFiles[i])
    }
})

这都是 Javascript 方面的。在您的 PHP 文件中,您可以处理文件并将其移动到服务器上的文件夹中:

<?php

    $folder_name = 'path-to-your-folder/';

    if (!empty($_FILES)) {
        $temp_file = $_FILES['file']['tmp_name'];
        $filename = $_POST['tags'].'.svg'; //Grabbing those tags that I appended to formData in the AJAX request and renaming the file based on those tags. Be sure to add your image extension
        $location = $folder_name.$filename;
        move_uploaded_file($temp_file, $location);
    }

?>

我希望这有帮助!=) 同样重要的是要注意,如果您希望在本地机器上测试 PHP 时运行 PHP,则必须在本地服务器上运行它。您可以按照这些说明设置本地服务器。

您可以使用 PHP 和 JS 从服务器取回图像并将其显示在客户端,但这可能超出了此问题的范围。如果您希望我添加它,只需在评论中提及它,我会将其添加为答案的更新。


推荐阅读