You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript缩略图关闭按钮异常:删除缩略图后选中图片数未减少

问题原因

原生<input type="file">的FilesList是只读对象,你删除缩略图时仅修改了自定义的imgArray和页面DOM,但原生输入框内的文件集合并未改变,因此提交时仍会带上所有初始选中的文件。另外当前代码通过文件名匹配删除文件,存在重名文件误删的风险。

解决方案

我们需要基于自定义的文件数组管理待上传文件,在表单提交时通过该数组构建FormData,而非依赖原生输入框的文件集合。同时修改缩略图绑定逻辑,用文件在数组中的索引关联,避免重名问题。

修改后的完整代码

HTML 部分

<form id="imageUploadForm" method="post" enctype="multipart/form-data">
  <div class="upload__box">
    <div class="upload__btn-box">
        <label class="form-label">Select Images</label>
        <input name="image_mul[]" type="file" class="form-control upload__inputfile" data-max_length="10" multiple accept="image/*">
    </div>
    <div class="upload__img-wrap"></div>
  </div>
  <button type="submit">Upload Images</button>
</form>

JavaScript 部分

jQuery(document).ready(function () {
  ImgUpload();
});

function ImgUpload() {
  $('.upload__inputfile').each(function () {
    const $input = $(this);
    const imgWrap = $input.closest('.upload__box').find('.upload__img-wrap');
    let imgArray = []; // 每个上传组件独立维护文件数组,避免全局冲突

    $input.on('change', function (e) {
      const maxLength = parseInt($input.attr('data-max_length')) || Infinity;
      const files = e.target.files;
      const filesArr = Array.prototype.slice.call(files);

      filesArr.forEach(function (f) {
        if (!f.type.match('image.*')) {
          return;
        }

        if (imgArray.length >= maxLength) {
          alert(`最多只能上传${maxLength}张图片`);
          return;
        }

        imgArray.push(f);
        const fileIndex = imgArray.length - 1; // 记录当前文件在数组中的索引

        const reader = new FileReader();
        reader.onload = function (e) {
          const html = `<div class='upload__img-box'>
            <div style='background-image: url(${e.target.result})' 
                 data-index='${fileIndex}' 
                 data-file='${f.name}' 
                 class='img-bg'>
              <div class='upload__img-close'></div>
            </div>
          </div>`;
          imgWrap.append(html);
        }
        reader.readAsDataURL(f);
      });
    });

    // 删除缩略图同步更新文件数组
    imgWrap.on('click', ".upload__img-close", function (e) {
      const fileIndex = parseInt($(this).parent().data("index"));
      imgArray.splice(fileIndex, 1);
      // 更新剩余缩略图的索引,避免后续删除出错
      imgWrap.find('.upload__img-box').each(function (idx) {
        $(this).find('.img-bg').data('index', idx);
      });
      $(this).parent().parent().remove();
    });

    // 自定义表单提交逻辑,仅提交保留的文件
    $input.closest('form').on('submit', function (e) {
      e.preventDefault();
      const formData = new FormData();
      
      imgArray.forEach(function(file) {
        formData.append('image_mul[]', file, file.name);
      });

      // 发送AJAX请求上传(可根据实际需求修改请求地址和回调逻辑)
      $.ajax({
        url: $(this).attr('action'),
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        success: function(response) {
          alert('上传成功');
          // 重置状态
          imgArray = [];
          imgWrap.empty();
          $input.val('');
        },
        error: function() {
          alert('上传失败');
        }
      });
    });
  });
}

关键修改说明

  • 独立文件数组:每个上传组件维护自己的imgArray,避免多个上传区域的文件数据冲突。
  • 索引关联文件:通过文件在数组中的索引绑定缩略图,彻底解决重名文件误删问题,删除后同步更新剩余缩略图的索引标记。
  • 自定义FormData提交:表单提交时基于imgArray构建上传数据,确保仅提交用户最终选择保留的文件。
  • 简化长度校验:直接通过imgArray.length判断是否超过上传数量上限,逻辑更清晰。

内容的提问来源于stack exchange,提问作者ITtraders Nepal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 10:50:22