Keeping selected images instead of replacing with the new ones

杀马特。学长 韩版系。学妹 提交于 2020-01-05 05:56:44

问题


I'm trying to create a HTML file input field which can add files (in this case images) multiple times, instead of replacing existing chosen files.

The file field will always replace the previous selection. What I am trying to do is store the selection somewhere else each time user selects a file.

$("#imageInput").change(function() {
    if(typeof window.images == "undefined"){
        window.images = this.files;
    }
    else {
        var k = 0;
        console.log(window.images.length); //always equals to this.files.length
        for (var i = window.images.length; i < window.images.length + this.files.length; i++) {
            window.images[i] = this.files[k];
            k++;
        }
    }
});

The HTML input tag:

<input type="file" id="imageInput" multiple accept="image/*">

This solutions doesn't work, because the window.images array is always reset when new files are choosen.


回答1:


indexOf :

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

  
     var images = [];
     var imagesName = [];
    $("#imageInput").change(function() {
       
        for(var i=0;i<this.files.length;i++)
        {  
              
             if(imagesName.indexOf(this.files[i].name)==-1)
             {
               console.log(this.files[i]);
               images.push(this.files[i]);
               imagesName.push(this.files[i].name);
             }
             
         }
        
        console.log(imagesName);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="file" id="imageInput" multiple accept="image/*">



回答2:


Found a solution. This works:

$("#imageInput").change(function() {
    var filesArr = Array.prototype.slice.call(this.files);
    filesArr.forEach(function(f) {
        window.images.push(f);
    });
    console.log(window.images);
});



回答3:


You're better off using Array.concat() to put all the new files on the end of the array:

window.images = [];
$("#imageInput").change(function() {
    window.images = window.images.concat(this.files);
});

If you're in ES6, you can use the spread operator and Array.push():

window.images = [];
$("#imageInput").change(function() {
    window.images.push(...this.files);
});

...which has the advantage of keeping the same array object, just making it longer.



来源:https://stackoverflow.com/questions/50957698/keeping-selected-images-instead-of-replacing-with-the-new-ones

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!