【问题标题】:How can I override default chrome file removal when cancelling a file choice for file inputs?取消文件输入的文件选择时,如何覆盖默认的 chrome 文件删除?
【发布时间】:2022-12-15 04:52:46
【问题描述】:

介绍

我已经为这个问题创建了一个解决方案,但我想让有同样问题的人可以解决这个问题,所以我会像我仍然有问题一样措辞。请在 cmets/answers 中提出对此问题的任何建议或替代解决方案。谢谢!

问题是什么?

在 Chrome 版本 108.0.5359.94(正式版)(x86_64) 中,当您尝试为先前分配的 <input type="file"> 更改文件并取消文件选择时,原始文件会消失。

有关于此的报告一会儿Chromium official forums 上,没有线索。我什至做了一个new issue,但被告知这个功能是通过设计, 所以很明显没有计划改变任何东西。

【问题讨论】:

    标签: javascript html jquery


    【解决方案1】:

    这不包括什么

    此解决方案不包括 Chrome 最初不引入此功能的原因,删除按钮。不过,考虑到这一点,删除按钮将是一个超级简单的实现。

    解决方案

    // Globally declare the array
    // If your javascript isn't refreshed each time you visit the inputs, you'll want to clear this on form submit
    array = []
    
    // Adding New file
    // Replacing current file
    $("input").change(function(event) {
        let file_list = event.target.files
        let key = event.target.id
    
            // When we change the files in our input, we persist the file by input; namely before assigning anything
            persist_file(array, file_list, key)
        
        // Assign the targets files to whatever is persisted for it
            event.target.files = array.find(obj => obj.key === key).file_list
    });
    
    // @doc Pushes or Replaces {key: <key>, file_list: <FileList>} objects into an array
    function persist_file(array, file_list, key) {
      if(file_list.length > 0) {
        if(member(array, key)) {
          array.find(obj => obj.key === key).file_list = file_list;
        }else {
          array.push({key: key, file_list: file_list})
        }
      }
    }
    
    // @doc Determines if the <key> exists in an object element of the <array>
    function member(array, key) {
        return array.some((element, index) => {
        return element.key == key
      })
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type='file' id="input_0"/><br>
    <input type='file' id="input_1"/><br>
    <input type='file' id="input_2"/>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 2013-04-22
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多