清除使用jquery从数组中删除的图像预览文件 [英] Clear an image preview file that was removed from the array with jquery

查看:78
本文介绍了清除使用jquery从数组中删除的图像预览文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚这个问题已经有一个多月了.在预览器上单击"x"后,我无法从阵列中删除该图像.

I tried to figure this out for over a month now. I cannot get the image to be removed from the array once the image was clicked on 'x' on the previewer.

http://jsfiddle.net/ERZVC/2/

我尝试使用接头失败!

$('#list').on('click', '.remove_img_preview',function () {
        $(this).parent('span').remove();

        //this is not working...
        var i = array.indexOf($(this));
        if(i != -1) {
            array.splice(i, 1);
        }
        // tried this too:
        //$(this).parent('span').splice( 1, 1 );

        count--;
    });

请帮帮我!

之所以需要将其从数组或输入文件列表中删除,是因为在提交表单时,它应仅上传预览器中的图像,而不是从预览器中删除的图像.

The reason I need it removed from the array or the input file list is because when submitting the form, it should only upload the images that are in the previewer and not the ones that were removed from it.

示例:如果我上传image1,image2,image3,然后删除image2,则仅应在提交时上传image1,image3.

Example: If I upload image1, image2, image3, then remove image2, it should only upload image1 and image3 on submission.

推荐答案

根据我对问题的了解,您正在尝试从多文件输入表单中删除文件.不幸的是,由于所有浏览器的安全性限制,这是不可能的.多文件输入返回只读 FileList,其中包含File个对象的集合.因此,您不能简单地从列表中删除一个元素. (结帐问题.)

From what I understand in your question, you're trying to remove a file from a multifile input form. Unfortunately this is not possible due to security restrictions in all browsers. The multifile input returns a read-only FileList, which contains a collection of File objects. Therefore you can't simply remove an element from the list. (Checkout this question.)

但是,有一种解决方法,它需要AJAX来处理表单.您可以处理FileList并将文件存储在数组中.然后附加一个on('submit')函数,该函数将拦截Submit操作. $.ajax()请求将代替发送事件,而是发送序列化表格.

There is a workaround, though, which requires AJAX for handling the form. You can process the FileList and store the files in an array. Then attach an on('submit') function which will intercept the submit action. Instead of a submit event, an $.ajax() request, sending the serialized form will be made.

示例:

<!-- upload.html -->
<!DOCTYPE html>
<html>
<head lang="en">
    <title>Upload</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

    <style type="text/css">
        ul{
            width: 650px;
        }
        ul li {
            list-style: none;
            width: 165px;
            float:left;
            position: relative;
            margin: 0px 0px 0px 20px;
        }

        .thumb {
            width: 150px;
        }

        .remove {
            position: absolute;
            top: 0px;
            right: 0px;
            color: red;
            cursor: pointer;
        }

        /* Prettify json output.. not needed in your code */
        pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
        .string { color: green; }
        .number { color: darkorange; }
        .boolean { color: blue; }
        .null { color: magenta; }
        .key { color: red; }

    </style>

    <script type="text/javascript">
        $(document).ready(function() {
            // You don't need this - it's used only for the demo.
            function jsonPrettify(json) {
                if (typeof json != 'string') {
                    json = JSON.stringify(json, undefined, 2);
                }
                json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
                    var cls = 'number';
                    if (/^"/.test(match)) {
                        if (/:$/.test(match)) {
                            cls = 'key';
                        } else {
                            cls = 'string';
                        }
                    } else if (/true|false/.test(match)) {
                        cls = 'boolean';
                    } else if (/null/.test(match)) {
                        cls = 'null';
                    }
                    return '<span class="' + cls + '">' + match + '</span>';
                });
            }
            // You don't need this - it's used only for the demo.



            // The code
            var filesArray = [];

            /**
             * This function processes all selected files
             *
             * @param e eventObject
             */
            function previewFiles( e ) {
                // FileList object
                var files = e.target.files;
                var preview = $('#imagePreviews');

                // Loop through the FileList and render image files as thumbnails.
                for (var i = 0, f; f = files[i]; i++) {

                    // Only process image files.
                    if (!f.type.match('image.*')) {
                        continue;
                    }

                    var reader = new FileReader();

                    // Closure to capture the file information.
                    reader.onload = (function(theFile) {
                        return function(e) {
                            // Render thumbnail.
                            var li = $('<li><img class="thumb" src="'+ e.target.result +'" title="'+ escape(theFile.name) +'"/><div class="remove">X</div></li>');
                            preview.append(li);

                            // Append image to array
                            filesArray.push(theFile);
                        };
                    })(f,preview);

                    // Read the image file as a data URL.
                    reader.readAsDataURL(f);
                }
            }
            // Attach on change to the file input
            $('#fileInput').on('change', previewFiles);

            /**
             * Remove the file from the array list.
             *
             * @param index integer
             */
            function removeFile( index ){
                filesArray.splice(index, 1);
            }
            // Attach on click listener which will handle the removing of images.
            $(document).on('click', '#imagePreviews .remove',function(e){
                var image = $(this).closest('li');

                console.log(image.index());

                // Remove the image from the array by getting it's index.
                // NOTE: The order of the filesArray will be the same as you see it displayed, therefore
                //       you simply need to get the file's index to "know" which item from the array to delete.
                console.log('Files:' ,filesArray);
                removeFile(image.index());
                console.log('Files:' ,filesArray);

                // Fadeout the image and remove it from the UI.
                image.fadeOut(function(){
                    $(this).remove();
                });
            });


            /**
             * This function processes the submission of the form.
             *
             * @param e
             */
            function submitForm(e){
                // Stop the form from actually submitting.
                e.preventDefault();

                // Create a new FormData based on our current form.
                // Makes live easier as we can attach a list of File objects.
                var formData = new FormData($('#myForm')[0]);
                for(var i= 0, file; file = filesArray[i]; i++){
                    formData.append('files[]', file);
                }

                // Send the ajax request.
                $.ajax({
                    url: 'upload.php',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        $('#response').html(jsonPrettify(response));
                    }
                });
            }
            // Attach on submit to the form submission.
            $('#myForm').on('submit', submitForm);
        });
    </script>

</head>

<body>

    <div style="width: 650px; border: 1px #D8D8D8;">

        <form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
            <label>Name</label>
            <input type="text" name="firstName" value="FirstName"/>
            <input type="text" name="lastName" value="LastName"/>

            <!-- Don't set a name of this input so that we won't need to remove it before serialization. -->
            <input id="fileInput" type="file" value="Upload button" multiple/>

            <div style="width: 600px; border: 1px solid #D8D8D8;">
                <ul style="list-style: none;" id="imagePreviews">
                </ul>

                <div style="clear: both;">&nbsp;</div>
            </div>

            <br>

            <input type="submit"/>

        </form>

        <br>
        Upload.php response<br>
        <pre id="response" style="width: 650px;"></pre>
    </div>

</body>
</html>


// upload.php
<?php

header('Content-Type: application/json');
echo json_encode(array('success' => true, '$_FILES' => $_FILES, '$_POST' => $_POST));

?>

希望这会有所帮助.

这篇关于清除使用jquery从数组中删除的图像预览文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆