简体   繁体   中英

Drag and Drop Html 5 file upload - Prevent loading

I have this code so far. I can see dragenter and dragleave events, but when I drop the file, the browser(Chrome or Firefox) just opens the file (a picture) even though preventDefault() is called. Anyone see any mistakes? What should I change?

 <script type="text/javascript">
    $(function () {
        var $box = $("#ulbox");
        $box.bind("dragenter", dragEnter);

        $box.bind("dragleave", dragLeave);
        $box.bind("drop", drop);

        function dragEnter(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            console.log("dragEnter...");
            $(evt.target).addClass('over');
            return false;
        }
        function dragLeave(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            console.log("drag leave...");
            $(evt.target).removeClass('over');
            return false;
        }


        function drop(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            $(evt.target).removeClass('over');

            var files = evt.originalEvent.dataTransfer.files;

            if (files.length > 0) {
                alert("dropped");
                if (window.FormData !== undefined) {
                    var data = new FormData();
                    for (i = 0; i < files.length; i++) {
                        data.append("file" + i, files[i]);
                    }

                    $.ajax({
                        type: "POST",
                        url: "/api/upload",
                        contentType: false,
                        processData: false,
                        data: data,
                        success: function (res) {
                        }
                    });
                } else {
                    alert("browser sucks!");
                }
            }
            return false;
        }
         });
    </script>
 }

 <div id="ulbox" style="border: 5px dashed black; width: 300px; height: 100px;">
 </div>

Remove $box.bind("dragleave", dragLeave);

Add this : $box.bind("dragover", dragLeave);

it works charms .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM