jquery - 带有删除选项的多个图像上传表单

时间:2014-03-28 17:21:06

标签: php jquery

我想要一些关于图像上传形式的建议,比如facebook和tumblr,它可以预览带有标题和描述字段的每个图像的多个图像,如果用户想要在上传之前删除任何图像,他就能够做到这一点。所以请建议我如何实现这一点我已经尝试过这个但是我遇到了从输入类型=文件中删除图像的问题,因为它是 readonly 我在服务器上提交表单时遇到问题。请给我你的想法我真的需要帮助我有这个月的截止日期我严重陷入这个问题。我正在使用php和jquery。 注意:请不要建议任何插件。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我遇到了和你一样的问题

现在我找到了解决方案,我认为这对你解决问题很有用

 <input type="file" id="attachfile" name="replyFiles" multiple> <!--File Element for multiple intput-->
 <div id="#filelist"></div>
 <script>
    var selDiv = "";
    var storedFiles = []; //store the object of the all files

    document.addEventListener("DOMContentLoaded", init, false); 

    function init() {
       //To add the change listener on over file element
       document.querySelector('#attachfile').addEventListener('change', handleFileSelect, false);
       //allocate division where you want to print file name
       selDiv = document.querySelector("#filelist");
    }

    //function to handle the file select listenere
    function handleFileSelect(e) {
       //to check that even single file is selected or not
       if(!e.target.files) return;      

       //for clear the value of the selDiv
       selDiv.innerHTML = "";

       //get the array of file object in files variable
       var files = e.target.files;
       var filesArr = Array.prototype.slice.call(files);

       //print if any file is selected previosly 
       for(var i=0;i<storedFiles.length;i++)
       {
           selDiv.innerHTML += "<div class='filename'> <span class='removefile'  data-file='"+storedFiles[i].name+"'> " + storedFiles[i].name + "</span></div>";
       }
       filesArr.forEach(function(f) {
           //add new selected files into the array list
           storedFiles.push(f);
           //print new selected files into the given division
           selDiv.innerHTML += "<div class='filename'> <span class='removefile'  data-file='"+storedFiles[i].name+"'> " + f.name + "</span></div>";
       });

       //store the array of file in our element this is send to other page by form submit
       $("input[name=replyfiles]").val(storedFiles);
 }

 //This function is used to remove the file form the selection   
 function removeFile(e) {
        var file = $(this).data("file"); //To take the name of the file

        for(var i=0;i<storedFiles.length;i++) { //for find the file from the array
            if(storedFiles[i].name === file) { 
                storedFiles.splice(i,1);   //remove file from the list
                break;
            }
        }

        //now store the list of the all remaining file in our element name which will submit with the form
        $("input[name=replyfiles]").val(storedFiles);    
        $(this).parent().remove();  
 }

 $(document).ready(function(){
     $("body").on("click", ".removefile", removeFile);
 })
 </script>