如何在dropzone.js中限制单文件上传并实现新文件自动替换原有文件
解决方案
你只需要修改dropzone_controller.js文件,添加自动移除旧文件的逻辑即可,具体修改如下:
1. 修改addedfile事件监听逻辑
在bindEvents方法的addedfile回调中添加超出文件数量限制时自动删除旧文件的逻辑,同时清理编辑页预加载的旧附件隐藏字段:
bindEvents() { this.dropZone.on("addedfile", file => { // 超出文件数量限制时自动移除最早上传的文件 if (this.dropZone.files.length > this.maxFiles) { const oldFile = this.dropZone.files[0]; this.dropZone.removeFile(oldFile); } // 清理编辑页预渲染的旧附件隐藏输入框 const oldHiddenInput = this.inputTarget.nextElementSibling; if (oldHiddenInput && oldHiddenInput.type === "hidden" && oldHiddenInput.name === this.inputTarget.name) { removeElement(oldHiddenInput); } setTimeout(() => { file.accepted && createDirectUploadController(this, file).start(); }, 500); }); this.dropZone.on("removedfile", file => { file.controller && removeElement(file.controller.hiddenInput); }); this.dropZone.on("canceled", file => { file.controller && file.controller.xhr.abort(); }); }
2. 适配编辑页已存在附件的场景
如果是编辑场景页面加载时已经存在已上传的附件,需要在connect方法中初始化Dropzone的文件计数,避免首次上传时没有触发替换逻辑:
connect() { this.dropZone = createDropZone(this); this.hideFileInput(); this.bindEvents(); Dropzone.autoDiscover = false; // 编辑页已存在附件时初始化文件计数 const hasExistingAttachment = this.element.querySelector('.attachment') !== null; if (hasExistingAttachment && this.maxFiles === 1) { // 占用一个文件名额,确保首次新上传会触发替换逻辑 this.dropZone.files = [{}]; } }
以上修改完成后即可实现需求:仅允许上传1个文件,新上传的文件会自动替换已有的旧文件,无需修改erb模板代码。
内容的提问来源于stack exchange,提问作者Денис Саєнко
相关产品推荐
相关产品推荐

