jQuery HTML5 file drag and drop

前端 未结 3 1211
鱼传尺愫
鱼传尺愫 2021-01-31 21:09

I have looked at many scripts for uploading images to the server with AJAX with drag and drop. The scripts I found are not jQuery, are quite large and don\'t do exactly what I w

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 22:13

    I wrote an extension for my application.

    // Custom file drop extension
    $.fn.extend({
        filedrop: function (options) {
            var defaults = {
                callback : null
            }
            options =  $.extend(defaults, options)
            return this.each(function() {
                var files = []
                var $this = $(this)
    
                // Stop default browser actions
                $this.bind('dragover dragleave', function(event) {
                    event.stopPropagation()
                    event.preventDefault()
                })
    
                // Catch drop event
                $this.bind('drop', function(event) {
                    // Stop default browser actions
                    event.stopPropagation()
                    event.preventDefault()
    
                    // Get all files that are dropped
                    files = event.originalEvent.target.files || event.originalEvent.dataTransfer.files
    
                    // Convert uploaded file to data URL and pass trought callback
                    if(options.callback) {
                        var reader = new FileReader()
                        reader.onload = function(event) {
                            options.callback(event.target.result)
                        }
                        reader.readAsDataURL(files[0])
                    }
                    return false
                })
            })
        }
    })
    

    And we can use it like this

    // Event listener filedropper
    $('.dropbox').filedrop({
        callback : function(fileEncryptedData) {
            // a callback?
        }
    })
    

    Edit

    If you want to drop multiple files, you should write a for loop around the FileReader like so:

    ...
    if(options.callback) {
        for (i = 0; i < files.length; i++) {
            var reader = new FileReader()
            reader.onload = function(event) {
                options.callback(event.target.result)
            }
            reader.readAsDataURL(files[0])
        }
    }
    ...
    

    JSFiddle: http://jsfiddle.net/646xe1m2/

提交回复
热议问题