【问题标题】:Multiple File Upload using dropzone and with other forms fields with FormValidation plugin使用 dropzone 和使用 FormValidation 插件的其他表单字段上传多个文件
【发布时间】:2021-12-07 01:00:58
【问题描述】:

这是我在项目中设计的表单图像现在我的要求是通过单个后端调用上传多个文件和其他表单值。

<script>
<form class="form-horizontal" name="addColorForm" id="addColorForm"
                          enctype="multipart/form-data"
                          method="POST">
  //Colour Name and Code fileds
  //Files Uploader Plugin  (Dropzone)
 <input type="file" name="artworkFiles[]" style="visibility: hidden"/>
</form>

现在是我的脚本部分

 <script>
    var validCode = function () { // my custom validation };
        FormValidation.validators.validCode = validCode;
        FormValidation.formValidation(
            document.getElementById('addColorForm'),
            {
                fields: {
                    colorName: {
                        validators: {
                            notEmpty: {
                                message: '${message(code:"blank.error.message", default:"This field must be entered")}'
                            },
                        }
                    },
                  },
                plugins: { //Learn more: https://formvalidation.io/guide/plugins
                    trigger: new FormValidation.plugins.Trigger(),
                    // Bootstrap Framework Integration
                    bootstrap: new FormValidation.plugins.Bootstrap(),
                    // Validate fields when clicking the Submit button
                    submitButton: new FormValidation.plugins.SubmitButton(),
                    // Submit the form when all fields are valid
                    // defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
                }
            }
        ).on('core.form.valid', function () {
            saveColor();
        });
    
        function saveColor() {
            var url = "url";
            var form = $("#createArtworkForm");
            var formData = new FormData(form[0]);
            $.ajax({
                url: url,
                type: 'POST',
                enctype: 'multipart/form-data',
                data: formData,
                success: function (data) {},
                cache: false,
                contentType: false,
                processData: false,
                error: function () { }
            });
        }

   var artworkColorsFiles = $('#kt_dropzone').dropzone({
    url: "https://www.google.com", // Set the url for your upload script location
    paramName: "media", // The name that will be used to transfer the file
    maxFiles: 1,
    maxFilesize: 40, // MB
    addRemoveLinks: true,
    acceptedFiles: "image/*",
    autoProcessQueue: false,
    accept: function (file) {
        //Logic to add multiple files in an input type hidden which is declared above
        let fileReader = new FileReader();

        fileReader.readAsDataURL(file);
        fileReader.onloadend = function () {

            let content = fileReader.result;
            $('#artworkFiles').val(content);
            file.previewElement.classList.add("dz-success");
        }
        file.previewElement.classList.add("dz-complete");
    }
 
});

</script>

我的问题是如何实现这一点,或者我应该如何在声明为可见性隐藏的输入类型文件字段中添加我的所有文件(最多 3 个)。

【问题讨论】:

    标签: javascript jquery grails dropzone.js formvalidation-plugin


    【解决方案1】:

    我在我的项目中所做的是代码,希望它对你有所帮助。 你必须使用 dropzone 函数在 sendingmultiple 函数中发送文件和表单数据你必须通过你的表单数据添加一个循环enter code here

    var data = $("form#OpportunityForm").serializeArray();
                    $.each(data, function (key, el) {
                            .append(el.name, el.value);
                    });
    
    
    
     $(document).ready(function () {
            zdrop = new Dropzone('#dropzone', {
                url: '@Url.Action("SaveOpportunity", "Masters")',
                maxFiles: 500,
                maxFilesize: 300,
                parallelUploads: 100,
                addRemoveLinks: true,
                autoProcessQueue: false,
                uploadMultiple: true,
                removeFilePromise: function () {
                    return new Promise((resolve, reject) => {
                        let rand = Math.floor(Math.random() * 3)
                        console.log(rand);
                        if (rand == 0) reject('didnt remove properly');
                        if (rand > 0) resolve();
                    });
                },
                sendingmultiple: function (file, xhr, formData) {
                    var data = $("form#OpportunityForm").serializeArray();
                    $.each(data, function (key, el) {
                            .append(el.name, el.value);
                    });
                    debugger
                    $("form#OpportunityForm").find("input[type=file]").each(function (index, field) {
                        const file = field.files[0];
                        formData.append('itemfile', file);
                    });
    
                },
                successmultiple: function (file, responseText) {
                    jQuery('form#OpportunityForm').find('textarea, input').each(function () {
                        jQuery(this).val('');
                    });
                    clear();
                    swal.fire("Opportunity Details Saved!", "Opportunity details Saved Successfully!", "success");
                    OpportunityMstList();
                    GetOpportunityMstList();
                    location.reload();
                    $("#myModal").modal('hide');
                },
            });
    

    在表单提交按钮上添加此按钮后,当您发布没有图像文件的数据时,您必须添加此按钮以创建 blob 文件。

      jQuery(document).on('click', 'button#saveOpportunity', function (e) {
        e.preventDefault();
        if ($("#OpportunityForm").validate().form()) {
            if (zdrop.files.length == 0) {
                var blob = new Blob();
                blob.upload = { 'chunked': zdrop.defaultOptions.chunking };
                zdrop.uploadFile(blob); // just submit the form
            } else if (zdrop.getRejectedFiles().length > 0) {
                alert("The attached file is invalid");
            } else {
                zdrop.processQueue();
            }
        }
    });
    

    【讨论】:

    • $.each 有错误
    • 请调试您的代码并检查您是否获取表单数据?
    • 我更新了表单提交按钮上的代码,如果未选择该文件,您必须创建一个 blob 文件。
    猜你喜欢
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 2018-12-01
    相关资源
    最近更新 更多