JQuery:如何将文件推送到另一个输入数组值?

JQuery: how can I push a file to another input array value?

我有 2 个输入:

每次,我 select 一些文件形成 temp,我想推送到另一个输入 files

我做这一步:

首先输入:

<input type="file" id="temp" name="temp[]" onchange="readFile(this);" multiple />

function readFile(input) {
    counter = input.files.length;
     for(x = 0; x<counter; x++){
        if (input.files && input.files[x]) {
           const  reader = new FileReader();

           reader.onload = function (e) {
              // add thumbnail picture
           }

           reader.readAsDataURL(input.files[x]);

        }
     }
}

我将此代码添加到主 js 函数中:

            var  new_file = [];
            new_file["id"] = "1";
            new_file["main"] = "0";
            new_file["delete"] = "0";
            new_file["file"] = input.files[x];
            files = $("input[name='files[]']").val();
            if(!Array.isArray(files)) files = [];
            files.push(new_file);
            $("input[name='files[]']").val(input[x]);

所以最终代码:

function readFile(input) {
    counter = input.files.length;
     for(x = 0; x<counter; x++){
        if (input.files && input.files[x]) {
           const  reader = new FileReader();

            var  new_file = [];
            new_file["id"] = "1";
            new_file["main"] = "0";
            new_file["delete"] = "0";
            new_file["file"] = input.files[x];
            files = $("input[name='files[]']").val();
            if(!Array.isArray(files)) files = [];
            files.push(new_file);
            $("input[name='files[]']").val(input[x]);

           reader.onload = function (e) {
              // add thumbnail picture
           }

           reader.readAsDataURL(input.files[x]);

        }
     }
}

所以我有两个问题:

在服务器端,我得到了这个:

 "files" => array:1 [▼
    0 => null
  ]

但温度还可以:

"temp" => array:1 [▼
    0 => UploadedFile {#1349 ▶}
 ]

此外,在行 new_file["file"] = input.files[x]; 中,input.files[x] 不是文件。它是一个对象。如何将文件插入 new_file["file"]?

You can't move the value of one file input to another, it is a security risk.

来自copying the value of a form's file input field to another form's input field


如果您想要实现的最终结果是当用户 select 文件用于 input[name="temp[]"] 时,两个文件输入具有相同的值,请考虑使用克隆和替换:

$('input[name="temp[]"]').change(function() {
  var $clone = $this.clone()
  $clone.attr('name', 'files[]');
  $('input[name="files[]"]').replaceWith($clone);
});