Dropzone Rails Gem如何实现0文件时正常提交表单请求
Dropzone 零文件提交表单实现方案
完全不需要编写和sendingmultiple逻辑重复的独立请求,只要对现有提交逻辑做少量调整即可兼容无文件场景,核心思路是在提交入口判断队列长度,同时抽离公共逻辑避免代码冗余。
问题原因
当前配置开启了autoProcessQueue: false,点击提交时直接调用processQueue(),当待上传队列文件数为0时,Dropzone不会发起任何请求,也不会触发sendingmultiple事件,导致表单卡住无响应。
具体实现
核心修改点:
- 把表单字段填充逻辑抽为公共函数,有文件上传、无文件直提两种场景复用同一段字段拼接代码
- 把提交成功后的跳转逻辑抽为公共函数,两种场景复用成功回调
- 提交按钮点击时先判断待上传文件数量:有文件走Dropzone原生上传流程,无文件时构造FormData直接请求同接口,复用所有配置和公共逻辑
- 原配置开启了
uploadMultiple: true,需要把原来监听的success事件替换为successmultiple,否则批量上传时会为每个文件触发一次成功回调,导致重复跳转。
修改后的完整配置代码如下:
Dropzone.options.dropzone = url: '/test/create' autoProcessQueue: false clickable: true uploadMultiple: true timeout: 180000 parallelUploads: 8 maxFiles: 8 maxFilesize: 5 acceptedFiles: 'image/*' addRemoveLinks: true headers: 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') init: -> dzClosure = this # 公共方法:统一填充所有表单字段 appendFormFields = (formData) -> formData.append 'item_number', jQuery('#item_number').val() # 其余原有表单字段追加逻辑全部迁移到此处 return # 公共方法:统一处理提交成功逻辑 onSubmitSuccess = (response) -> window.location.href = url return document.getElementById('submit-button').addEventListener 'click', (e) -> e.preventDefault() e.stopPropagation() queuedFileCount = dzClosure.getQueuedFiles().length if queuedFileCount > 0 # 存在待上传文件,走Dropzone原生上传队列 dzClosure.processQueue() else # 无文件时直接提交表单数据,复用Dropzone的接口、请求头配置 emptyForm = new FormData() appendFormFields(emptyForm) jQuery.ajax url: dzClosure.options.url type: 'POST' data: emptyForm processData: false contentType: false headers: dzClosure.options.headers success: onSubmitSuccess return @on 'sendingmultiple', (data, xhr, formData) -> appendFormFields(formData) return # 多文件批量上传完成后触发成功回调,替换原单文件success监听 @on 'successmultiple', (files, responseText) -> onSubmitSuccess(responseText) return return
额外说明
- 无文件提交时直接读取Dropzone配置里的
url、headers参数,后续修改接口地址、认证信息不需要维护两处代码 - 所有表单字段的拼接逻辑统一维护,不会出现有文件、无文件提交时字段不一致的问题
- 不需要修改后端接口逻辑,后端只需要和原来一样处理FormData参数即可,无文件时不会接收到文件参数,符合图片非必填的业务预期
内容的提问来源于stack exchange,提问作者TheMangaStand
相关产品推荐
相关产品推荐

