LoginSignup
2
2

More than 5 years have passed since last update.

HTML5 D&Dによるファイルアップロード

Last updated at Posted at 2013-05-24
(function ($) {
    $.fn.upload = function(options) {
        var defer = $.Deferred();
        var settings = {
            url: null,
            urlBase: null
        };
        if (options) {
            $.extend(settings, options);
        }

        var $this = $(this);

        $this.on('dragenter dragover', function() {
            return false;
        });
        $this.on('drop', function(e) {
            e.preventDefault();

            var file = e.originalEvent.dataTransfer.files[0];
            var reader = new FileReader();

            reader.onload = function(e) {
                var xhr = new XMLHttpRequest();
                var url = settings.url;

                xhr.open('POST', url, true);

                var filetype = file.type;

                if (_.isEmpty(filetype)) {
                    filetype = 'application/octet-stream';
                }

                xhr.setRequestHeader('Content-Type', filetype);

                xhr.onload = function(e) {
                    if (this.status === 200) {
                        return defer.resolve();
                    } else {
                        return defer.reject();
                    }
                };

                xhr.send(file);
            };

            reader.readAsBinaryString(file);
        });

        return defer.promise();
    };
})(jQuery);
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2