0

I have 2 inputs:

each time, I select some files form temp and I want push to another input files.

I do this step:

chage first iput:

<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]);

        }
     }
}

I add this code to main js fuction:

            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]);

So finall code:

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]);

        }
     }
}

So I have 2 problem:

in server side, I got this:

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

but temp is ok:

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

Also, in line new_file["file"] = input.files[x];, input.files[x] is not a file. it is an object. how can insert file to new_file["file"]?

ali ali
  • 161
  • 2
  • 8
  • 1
    The value of a file input is not file object. This is an [XY Problem](http://xyproblem.info/) . What exactly are you trying to accomplish? You can't programmatically add files to an input for security reasons – charlietfl Aug 24 '19 at 17:58

1 Answers1

1

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

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


If the end result you want to achieve is to have identical values for both the file inputs when user select files for input[name="temp[]"], consider using clone and replace instead:

$('input[name="temp[]"]').change(function() {
  var $clone = $this.clone()
  $clone.attr('name', 'files[]');
  $('input[name="files[]"]').replaceWith($clone);
});
Wei Seng Tan
  • 487
  • 3
  • 8