Jquery add file object to filelist object

I am trying to create a simple image downloader for my site, but I have one problem. When I want to add my new image to the previous selected image, you cannot store the old selected images (because a new FileList object has been created), and then send them all to my controller and my problem, adding the old "file object" to the new " FileList 'Objects'. HTML:

<div id="filediv">
    <input type="file" id="file" name="files[]" multiple="multiple" />
</div>

script:

window.filesToUpload = [];
window.tmp = [];
$("#file").on('change', function () {
    "use strict";

    if (window.filesToUpload.length > 0) {
        $.each(window.tmp, function (i, img) {

I want to add an old file object to a new FileList object HERE

        });
    }

    if (this.files.length >= 1) {
        $("[id^=previewImg]").remove();
        $.each(this.files, function (i, img) {
            window.tmp.push(img);

            var reader = new FileReader(),
                newElement = $("<div id='previewImg" + i + "' class='abcd'><img /></div>"),
                preview = newElement.find("img");

            reader.onloadend = function () {
                preview.attr("src", reader.result);
                preview.attr("alt", img.name);
            };

            try {
                window.filesToUpload.push(document.getElementById("file").files[i]);
            } catch (e) {
                console.log(e.message);
            }

            if (img) {
                reader.readAsDataURL(img);
            } else {
                preview.src = "";
            }


            newElement.appendTo("#filediv");
        });
    }
});
+4
source share

Source: https://habr.com/ru/post/1672000/


All Articles