javascript - 如何将FileList数组添加到<input type ='file'>控件中?

标签 javascript jquery arrays file filelist

在这种情况下,我有两个文件类型输入控件。

Html:

<input type="file" id="file1" multiple="multiple" />
<input type="file" id="file2" multiple="multiple" />
<input id="btn1" type="button" />

Script:

<script>
var fileList = [];
$('#file1').change(function (e) {
   var files = e.target.files;
            $.each(files, function (k, v) {
                fileList.push(files[k]);
            });
});
$('#btn1').click(function(){
  //Stuffs to be added for pushing the array of File object from "fileList" array to "file2"
  //How to achieve it or is that impossible to do it?
});
</script>

我想实现以下步骤:

第 1 步:在“file1”输入更改时,它将文件推送到数组中。

第 2 步:在单击“btn1”按钮时,我需要将 File 对象数组设置或推送到“file2” 输入控制。但我做不到,我已经用谷歌搜索了。我没有找到解决方案。

我无法实现第 2 步,请帮助我。

还提供一些可能对我有帮助的链接。

最佳答案

嗯,答案是使用 DataTransfer 对象。

// first create a var DataTransfer
/*
Used to hold the data that is being dragged
during a drag and drop operation. 
It may hold one or more data items,
each of one or more data types. 
For more information about drag and drop, 
see HTML Drag and Drop API.
*/
let data = new DataTransfer();

// now you need to iterate this
let el = document.getElementById("#myInput");
 for (let c = 0; c < el.files.length; c++) {
        // @ts-ignore
        let file = el.files[c];
        data.items.add(file);
      }

// then you can put the data files to any input file you want
let el2 =  document.getElementById("#myInput2");
el2.files = data.files;

额外:如果你想切片文件数据,你需要使用 for 循环,数组的切片方法不适用于它。

// this snippet slices a data transfer alike data.slice(0,4)

let t = data.items.length;
for (let c = 0; c < t; c++) {
        c >= 4 && data.items.remove(c);
      }

最诚挚的问候

关于javascript - 如何将FileList数组添加到&lt;input type ='file'>控件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25658898/

相关文章:

javascript - SCSS根据id添加动画

jQuery slider 不适用于网站

javascript - 我的 Modal 无法在 Bootstrap 中工作,看不出出了什么问题

c - c中的数组名到底是什么?

javascript - 使用php没有记录列时如何禁用按钮?

php - 在 window.location.href 中使用 php

javascript - 匹配更多可能性的正则表达式(javascript)

jquery - iOS7 - jquery.touchSwipe 干扰点击和 webkit-touch-callout

javascript - 在 Javascript 中推送对象

javascript - 按元素的出现对数组进行排序