本文介绍了保留选定的图像,而不是用新图像替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个HTML文件输入字段,该字段可以多次添加文件(在这种情况下为图像),而不是替换现有的选定文件.

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++;
        }
    }
});

HTML输入标签:

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

该解决方案不起作用,因为选择新文件时,总是重置window.images数组.

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

推荐答案

indexOf:


     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/*">

这篇关于保留选定的图像,而不是用新图像替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 02:37