var MediaUpload = View.extend({ el: ".fileUpload", createAction: "/api/media/new", uploadAction: "/api/media/upload", events: { "keydown .url": "enterSubmit", "change .file": "handleFileSelect", "submit form": "preventDefault", }, initialize: function(opt){ this.parent = opt.parent this.$csrf = this.$("[name=_csrf]") this.$url = this.$(".url") this.$file = this.$(".file") this.$upload = this.$(".upload-icon") }, show: function(){ this.$el.addClass("active") this.$url.val("") }, hide: function(){ this.$el.removeClass("active") }, enterSubmit: function(e){ if (e.keyCode == 13) { e.preventDefault() this.parse() } }, parse: function(){ var url = this.$url.val() this.$url.val("") Parser.parse(url, $.proxy(function(media){ if (! media) { alert("Not a valid image/video link") return } media._csrf = this.$csrf.val() console.log(media) var request = $.ajax({ type: "post", url: this.createAction, data: media, }) request.done($.proxy(this.add, this)) }, this)) }, handleFileSelect: function(e) { e.stopPropagation(); e.preventDefault(); this.parent.mediaViewer.deleteArmed(false) var files = e.dataTransfer ? e.dataTransfer.files : e.target.files; for (var i = 0, f; f = files[i]; i++) { if ( ! f.type.match('image.*')) { continue; } this.getImageDimensions(f) } }, getImageDimensions: function(f){ var base = this this.$upload.addClass('uploading') var reader = new FileReader(); reader.onload = function(e) { var image = new Image() image.onload = function(){ var width = image.naturalWidth, height = image.naturalHeight base.upload(f, width, height) } image.src = e.target.result } reader.readAsDataURL(f); }, upload: function(f, width, height){ var fd = new FormData() fd.append('image', f) fd.append('width', width) fd.append('height', height) fd.append('_csrf', this.$csrf.val()) var request = $.ajax({ url: this.uploadAction, type: "post", data: fd, dataType: "json", processData: false, contentType: false, }) request.done($.proxy(this.add, this)) }, add: function(media){ console.log(media) if (media.error) { return } this.$upload.removeClass('uploading') this.parent.mediaViewer.add(media) } })