diff --git a/src/main/scala/app/ControllerBase.scala b/src/main/scala/app/ControllerBase.scala index 34ad4ce..5a2a4b0 100644 --- a/src/main/scala/app/ControllerBase.scala +++ b/src/main/scala/app/ControllerBase.scala @@ -11,8 +11,7 @@ import org.apache.commons.io.FileUtils import model.Account import service.{SystemSettingsService, AccountService} -import javax.servlet.http.{HttpServletResponse, HttpSession, HttpServletRequest} -import java.text.SimpleDateFormat +import javax.servlet.http.{HttpServletResponse, HttpServletRequest} import javax.servlet.{FilterChain, ServletResponse, ServletRequest} import org.scalatra.i18n._ @@ -164,7 +163,7 @@ /** * Base trait for controllers which manages account information. */ -trait AccountManagementControllerBase extends ControllerBase with FileUploadControllerBase { +trait AccountManagementControllerBase extends ControllerBase { self: AccountService => protected def updateImage(userName: String, fileId: Option[String], clearImage: Boolean): Unit = @@ -175,9 +174,9 @@ } } else { fileId.map { fileId => - val filename = "avatar." + FileUtil.getExtension(getUploadedFilename(fileId).get) + val filename = "avatar." + FileUtil.getExtension(session.getAndRemove(Keys.Session.Upload(fileId)).get) FileUtils.moveFile( - getTemporaryFile(fileId), + new java.io.File(getTemporaryDir(session.getId), fileId), new java.io.File(getUserUploadDir(userName), filename) ) updateAvatarImage(userName, Some(filename)) @@ -197,28 +196,3 @@ } } - -/** - * Base trait for controllers which needs file uploading feature. - */ -trait FileUploadControllerBase { - - def generateFileId: String = - new SimpleDateFormat("yyyyMMddHHmmSSsss").format(new java.util.Date(System.currentTimeMillis)) - - def TemporaryDir(implicit session: HttpSession): java.io.File = - new java.io.File(GitBucketHome, s"tmp/_upload/${session.getId}") - - def getTemporaryFile(fileId: String)(implicit session: HttpSession): java.io.File = - new java.io.File(TemporaryDir, fileId) - - // def removeTemporaryFile(fileId: String)(implicit session: HttpSession): Unit = - // getTemporaryFile(fileId).delete() - - def removeTemporaryFiles()(implicit session: HttpSession): Unit = - FileUtils.deleteDirectory(TemporaryDir) - - def getUploadedFilename(fileId: String)(implicit session: HttpSession): Option[String] = - session.getAndRemove[String](Keys.Session.Upload(fileId)) - -} \ No newline at end of file diff --git a/src/main/scala/app/FileUploadController.scala b/src/main/scala/app/FileUploadController.scala index 9950b48..ad8ea28 100644 --- a/src/main/scala/app/FileUploadController.scala +++ b/src/main/scala/app/FileUploadController.scala @@ -1,31 +1,42 @@ package app -import _root_.util.{Keys, FileUtil} +import util.{Keys, FileUtil} import util.ControlUtil._ +import util.Directory._ import org.scalatra._ -import org.scalatra.servlet.{MultipartConfig, FileUploadSupport} +import org.scalatra.servlet.{MultipartConfig, FileUploadSupport, FileItem} import org.apache.commons.io.FileUtils /** * Provides Ajax based file upload functionality. * - * This servlet saves uploaded file as temporary file and returns the unique id. - * You can get uploaded file using [[app.FileUploadControllerBase#getTemporaryFile()]] with this id. + * This servlet saves uploaded file. */ -class FileUploadController extends ScalatraServlet with FileUploadSupport with FileUploadControllerBase { +class FileUploadController extends ScalatraServlet with FileUploadSupport { configureMultipartHandling(MultipartConfig(maxFileSize = Some(3 * 1024 * 1024))) post("/image"){ - fileParams.get("file") match { - case Some(file) if(FileUtil.isImage(file.name)) => defining(generateFileId){ fileId => - FileUtils.writeByteArrayToFile(getTemporaryFile(fileId), file.get) - session += Keys.Session.Upload(fileId) -> file.name - Ok(fileId) - } - case None => BadRequest + execute { (file, fileId) => + FileUtils.writeByteArrayToFile(new java.io.File(getTemporaryDir(session.getId), fileId), file.get) + session += Keys.Session.Upload(fileId) -> file.name } } -} + post("/image/:owner/:repository"){ + execute { (file, fileId) => + FileUtils.writeByteArrayToFile(new java.io.File(getAttachedDir(params("owner"), params("repository")), fileId), file.get) + } + } + private def execute(f: (FileItem, String) => Unit) = fileParams.get("file") match { + case Some(file) if(FileUtil.isImage(file.name)) => + defining(FileUtil.generateFileId){ fileId => + f(file, fileId) + + Ok(fileId) + } + case _ => BadRequest + } + +} diff --git a/src/main/scala/app/IssuesController.scala b/src/main/scala/app/IssuesController.scala index 7dc634c..61bd52f 100644 --- a/src/main/scala/app/IssuesController.scala +++ b/src/main/scala/app/IssuesController.scala @@ -273,6 +273,12 @@ } }) + get("/:owner/:repository/_attached/:file")(referrersOnly { repository => + defining(new java.io.File(Directory.getAttachedDir(repository.owner, repository.name), params("file"))){ file => + if(file.exists) file else NotFound + } + }) + val assignedUserName = (key: String) => params.get(key) filter (_.trim != "") val milestoneId: String => Option[Int] = (key: String) => params.get(key).flatMap(_.toIntOpt) diff --git a/src/main/scala/servlet/SessionCleanupListener.scala b/src/main/scala/servlet/SessionCleanupListener.scala index 87ce1d1..ee4ea7b 100644 --- a/src/main/scala/servlet/SessionCleanupListener.scala +++ b/src/main/scala/servlet/SessionCleanupListener.scala @@ -1,15 +1,16 @@ package servlet import javax.servlet.http.{HttpSessionEvent, HttpSessionListener} -import app.FileUploadControllerBase +import org.apache.commons.io.FileUtils +import util.Directory._ /** * Removes session associated temporary files when session is destroyed. */ -class SessionCleanupListener extends HttpSessionListener with FileUploadControllerBase { +class SessionCleanupListener extends HttpSessionListener { def sessionCreated(se: HttpSessionEvent): Unit = {} - def sessionDestroyed(se: HttpSessionEvent): Unit = removeTemporaryFiles()(se.getSession) + def sessionDestroyed(se: HttpSessionEvent): Unit = FileUtils.deleteDirectory(getTemporaryDir(se.getSession.getId)) } diff --git a/src/main/scala/util/Directory.scala b/src/main/scala/util/Directory.scala index d37577a..1d15f1a 100644 --- a/src/main/scala/util/Directory.scala +++ b/src/main/scala/util/Directory.scala @@ -29,24 +29,10 @@ }).getAbsolutePath val GitBucketConf = new File(GitBucketHome, "gitbucket.conf") - + val RepositoryHome = s"${GitBucketHome}/repositories" val DatabaseHome = s"${GitBucketHome}/data" - - /** - * Repository names of the specified user. - */ - def getRepositories(owner: String): List[String] = - defining(new File(s"${RepositoryHome}/${owner}")){ dir => - if(dir.exists){ - dir.listFiles.filter { file => - file.isDirectory && !file.getName.endsWith(".wiki.git") - }.map(_.getName.replaceFirst("\\.git$", "")).toList - } else { - Nil - } - } /** * Substance directory of the repository. @@ -55,11 +41,23 @@ new File(s"${RepositoryHome}/${owner}/${repository}.git") /** + * Directory for files which are attached to issue. + */ + def getAttachedDir(owner: String, repository: String): File = + new File(s"${RepositoryHome}/${owner}/${repository}/issues") + + /** * Directory for uploaded files by the specified user. */ def getUserUploadDir(userName: String): File = new File(s"${GitBucketHome}/data/${userName}/files") /** + * Root of temporary directories for the upload file. + */ + def getTemporaryDir(sessionId: String): File = + new File(s"${GitBucketHome}/tmp/_upload/${sessionId}") + + /** * Root of temporary directories for the specified repository. */ def getTemporaryDir(owner: String, repository: String): File = diff --git a/src/main/scala/util/FileUtil.scala b/src/main/scala/util/FileUtil.scala index f3bba07..0145db4 100644 --- a/src/main/scala/util/FileUtil.scala +++ b/src/main/scala/util/FileUtil.scala @@ -4,9 +4,10 @@ import java.net.URLConnection import java.io.File import util.ControlUtil._ +import scala.util.Random object FileUtil { - + def getMimeType(name: String): String = defining(URLConnection.getFileNameMap()){ fileNameMap => fileNameMap.getContentTypeFor(name) match { @@ -26,14 +27,12 @@ } def isImage(name: String): Boolean = getMimeType(name).startsWith("image/") - + def isLarge(size: Long): Boolean = (size > 1024 * 1000) - + def isText(content: Array[Byte]): Boolean = !content.contains(0) - def getFileName(path: String): String = defining(path.lastIndexOf('/')){ i => - if(i >= 0) path.substring(i + 1) else path - } + def generateFileId: String = System.currentTimeMillis + Random.alphanumeric.take(10).mkString def getExtension(name: String): String = name.lastIndexOf('.') match { diff --git a/src/main/twirl/helper/attached.scala.html b/src/main/twirl/helper/attached.scala.html new file mode 100644 index 0000000..7ae78c9 --- /dev/null +++ b/src/main/twirl/helper/attached.scala.html @@ -0,0 +1,24 @@ +@(owner: String, repository: String)(textarea: Html)(implicit context: app.Context) +@import context._ +
+ @textarea + Attach images by dragging & dropping, or selecting them. +
+@defining("(id=\")([\\w\\-]*)(\")".r.findFirstMatchIn(textarea.body).map(_.group(2))){ textareaId => + +} diff --git a/src/main/twirl/helper/preview.scala.html b/src/main/twirl/helper/preview.scala.html index cc6504b..639acd9 100644 --- a/src/main/twirl/helper/preview.scala.html +++ b/src/main/twirl/helper/preview.scala.html @@ -6,16 +6,18 @@
- + @textarea = { + + } + @if(enableWikiLink){ + @textarea + } else { + @helper.html.attached(repository.owner, repository.name)(textarea) + }
diff --git a/src/main/twirl/helper/uploadavatar.scala.html b/src/main/twirl/helper/uploadavatar.scala.html index f1a58f3..5de7ae4 100644 --- a/src/main/twirl/helper/uploadavatar.scala.html +++ b/src/main/twirl/helper/uploadavatar.scala.html @@ -21,7 +21,6 @@ var dropzone = new Dropzone('div#clickable', { url: '@path/upload/image', previewsContainer: 'div#avatar', - paramName: 'file', parallelUploads: 1, thumbnailWidth: 120, thumbnailHeight: 120 diff --git a/src/main/twirl/issues/editcomment.scala.html b/src/main/twirl/issues/editcomment.scala.html index 1539f81..e631872 100644 --- a/src/main/twirl/issues/editcomment.scala.html +++ b/src/main/twirl/issues/editcomment.scala.html @@ -1,7 +1,9 @@ @(content: String, commentId: Int, owner: String, repository: String)(implicit context: app.Context) @import context._ - +@helper.html.attached(owner, repository){ + +}
diff --git a/src/main/twirl/issues/editissue.scala.html b/src/main/twirl/issues/editissue.scala.html index 80554f7..b97d1f5 100644 --- a/src/main/twirl/issues/editissue.scala.html +++ b/src/main/twirl/issues/editissue.scala.html @@ -2,7 +2,9 @@ @import context._ - +@helper.html.attached(owner, repository){ + +}
diff --git a/src/main/webapp/assets/common/js/dropzone.js b/src/main/webapp/assets/common/js/dropzone.js index d98c8ed..d835bb2 100644 --- a/src/main/webapp/assets/common/js/dropzone.js +++ b/src/main/webapp/assets/common/js/dropzone.js @@ -1,36 +1,22 @@ + ;(function(){ /** - * Require the given path. + * Require the module at `name`. * - * @param {String} path + * @param {String} name * @return {Object} exports * @api public */ -function require(path, parent, orig) { - var resolved = require.resolve(path); +function require(name) { + var module = require.modules[name]; + if (!module) throw new Error('failed to require "' + name + '"'); - // lookup failed - if (null == resolved) { - orig = orig || path; - parent = parent || 'root'; - var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); - err.path = orig; - err.parent = parent; - err.require = true; - throw err; - } - - var module = require.modules[resolved]; - - // perform real require() - // by invoking the module's - // registered function - if (!module.exports) { - module.exports = {}; + if (!('exports' in module) && typeof module.definition === 'function') { module.client = module.component = true; - module.call(this, module.exports, require.relative(resolved), module); + module.definition.call(this, module.exports = {}, module); + delete module.definition; } return module.exports; @@ -43,160 +29,33 @@ require.modules = {}; /** - * Registered aliases. - */ - -require.aliases = {}; - -/** - * Resolve `path`. + * Register module at `name` with callback `definition`. * - * Lookup: - * - * - PATH/index.js - * - PATH.js - * - PATH - * - * @param {String} path - * @return {String} path or null - * @api private - */ - -require.resolve = function(path) { - if (path.charAt(0) === '/') path = path.slice(1); - - var paths = [ - path, - path + '.js', - path + '.json', - path + '/index.js', - path + '/index.json' - ]; - - for (var i = 0; i < paths.length; i++) { - var path = paths[i]; - if (require.modules.hasOwnProperty(path)) return path; - if (require.aliases.hasOwnProperty(path)) return require.aliases[path]; - } -}; - -/** - * Normalize `path` relative to the current path. - * - * @param {String} curr - * @param {String} path - * @return {String} - * @api private - */ - -require.normalize = function(curr, path) { - var segs = []; - - if ('.' != path.charAt(0)) return path; - - curr = curr.split('/'); - path = path.split('/'); - - for (var i = 0; i < path.length; ++i) { - if ('..' == path[i]) { - curr.pop(); - } else if ('.' != path[i] && '' != path[i]) { - segs.push(path[i]); - } - } - - return curr.concat(segs).join('/'); -}; - -/** - * Register module at `path` with callback `definition`. - * - * @param {String} path + * @param {String} name * @param {Function} definition * @api private */ -require.register = function(path, definition) { - require.modules[path] = definition; +require.register = function (name, definition) { + require.modules[name] = { + definition: definition + }; }; /** - * Alias a module definition. + * Define a module's exports immediately with `exports`. * - * @param {String} from - * @param {String} to + * @param {String} name + * @param {Generic} exports * @api private */ -require.alias = function(from, to) { - if (!require.modules.hasOwnProperty(from)) { - throw new Error('Failed to alias "' + from + '", it does not exist'); - } - require.aliases[to] = from; -}; - -/** - * Return a require function relative to the `parent` path. - * - * @param {String} parent - * @return {Function} - * @api private - */ - -require.relative = function(parent) { - var p = require.normalize(parent, '..'); - - /** - * lastIndexOf helper. - */ - - function lastIndexOf(arr, obj) { - var i = arr.length; - while (i--) { - if (arr[i] === obj) return i; - } - return -1; - } - - /** - * The relative require() itself. - */ - - function localRequire(path) { - var resolved = localRequire.resolve(path); - return require(resolved, parent, path); - } - - /** - * Resolve relative to the parent. - */ - - localRequire.resolve = function(path) { - var c = path.charAt(0); - if ('/' == c) return path.slice(1); - if ('.' == c) return require.normalize(p, path); - - // resolve deps by returning - // the dep in the nearest "deps" - // directory - var segs = parent.split('/'); - var i = lastIndexOf(segs, 'deps') + 1; - if (!i) i = 0; - path = segs.slice(0, i + 1).join('/') + '/deps/' + path; - return path; +require.define = function (name, exports) { + require.modules[name] = { + exports: exports }; - - /** - * Check if module is defined at `path`. - */ - - localRequire.exists = function(path) { - return require.modules.hasOwnProperty(localRequire.resolve(path)); - }; - - return localRequire; }; -require.register("component-emitter/index.js", function(exports, require, module){ +require.register("component~emitter@1.1.2", function (exports, module) { /** * Expose `Emitter`. @@ -238,7 +97,8 @@ * @api public */ -Emitter.prototype.on = function(event, fn){ +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); @@ -264,7 +124,7 @@ fn.apply(this, arguments); } - fn._off = on; + on.fn = fn; this.on(event, on); return this; }; @@ -281,8 +141,17 @@ Emitter.prototype.off = Emitter.prototype.removeListener = -Emitter.prototype.removeAllListeners = function(event, fn){ +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; @@ -293,8 +162,14 @@ } // remove specific handler - var i = callbacks.indexOf(fn._off || fn); - if (~i) callbacks.splice(i, 1); + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } return this; }; @@ -347,50 +222,52 @@ }; }); -require.register("dropzone/index.js", function(exports, require, module){ + +require.register("dropzone", function (exports, module) { /** * Exposing dropzone */ -module.exports = require("./lib/dropzone.js"); +module.exports = require("dropzone/lib/dropzone.js"); }); -require.register("dropzone/lib/dropzone.js", function(exports, require, module){ -/* -# -# More info at [www.dropzonejs.com](http://www.dropzonejs.com) -# -# Copyright (c) 2012, Matias Meno -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -*/ +require.register("dropzone/lib/dropzone.js", function (exports, module) { + +/* + * + * More info at [www.dropzonejs.com](http://www.dropzonejs.com) + * + * Copyright (c) 2012, Matias Meno + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ (function() { - var Dropzone, Em, camelize, contentLoaded, noop, without, + var Dropzone, Em, camelize, contentLoaded, detectVerticalSquash, drawImageIOSFix, noop, without, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __slice = [].slice; - Em = typeof Emitter !== "undefined" && Emitter !== null ? Emitter : require("emitter"); + Em = typeof Emitter !== "undefined" && Emitter !== null ? Emitter : require("component~emitter@1.1.2"); noop = function() {}; @@ -399,16 +276,16 @@ __extends(Dropzone, _super); + /* This is a list of all available events you can register on a dropzone object. You can register an event handler like this: dropzone.on("dragEnter", function() { }); - */ + */ - - Dropzone.prototype.events = ["drop", "dragstart", "dragend", "dragenter", "dragover", "dragleave", "selectedfiles", "addedfile", "removedfile", "thumbnail", "error", "processing", "processingmultiple", "uploadprogress", "totaluploadprogress", "sending", "sendingmultiple", "success", "successmultiple", "canceled", "canceledmultiple", "complete", "completemultiple", "reset"]; + Dropzone.prototype.events = ["drop", "dragstart", "dragend", "dragenter", "dragover", "dragleave", "addedfile", "removedfile", "thumbnail", "error", "errormultiple", "processing", "processingmultiple", "uploadprogress", "totaluploadprogress", "sending", "sendingmultiple", "success", "successmultiple", "canceled", "canceledmultiple", "complete", "completemultiple", "reset", "maxfilesexceeded", "maxfilesreached"]; Dropzone.prototype.defaultOptions = { url: null, @@ -422,6 +299,7 @@ maxThumbnailFilesize: 10, thumbnailWidth: 100, thumbnailHeight: 100, + maxFiles: null, params: {}, clickable: true, ignoreHiddenFiles: true, @@ -433,12 +311,14 @@ dictDefaultMessage: "Drop files here to upload", dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.", dictFallbackText: "Please use the fallback form below to upload your files like in the olden days.", - dictFileTooBig: "File is too big ({{filesize}}MB). Max filesize: {{maxFilesize}}MB.", + dictFileTooBig: "File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.", dictInvalidFileType: "You can't upload files of this type.", dictResponseError: "Server responded with {{statusCode}} code.", dictCancelUpload: "Cancel upload", dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?", dictRemoveFile: "Remove file", + dictRemoveFileConfirmation: null, + dictMaxFilesExceeded: "You can not upload any more files.", accept: function(file, done) { return done(); }, @@ -494,6 +374,7 @@ info.srcY = (file.height - info.srcHeight) / 2; return info; }, + /* Those functions register themselves to the events on init and handle all the user interface specific stuff. Overwriting them won't break the upload @@ -501,8 +382,7 @@ You can overwrite them if you don't like the default behavior. If you just want to add an additional event handler, register it on the dropzone object and don't overwrite those options. - */ - + */ drop: function(e) { return this.element.classList.remove("dz-drag-hover"); }, @@ -519,53 +399,94 @@ dragleave: function(e) { return this.element.classList.remove("dz-drag-hover"); }, - selectedfiles: function(files) { - if (this.element === this.previewsContainer) { - return this.element.classList.add("dz-started"); - } - }, + paste: noop, reset: function() { return this.element.classList.remove("dz-started"); }, addedfile: function(file) { - var _this = this; - file.previewElement = Dropzone.createElement(this.options.previewTemplate); + var node, removeFileEvent, removeLink, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _results; + if (this.element === this.previewsContainer) { + this.element.classList.add("dz-started"); + } + file.previewElement = Dropzone.createElement(this.options.previewTemplate.trim()); file.previewTemplate = file.previewElement; this.previewsContainer.appendChild(file.previewElement); - file.previewElement.querySelector("[data-dz-name]").textContent = file.name; - file.previewElement.querySelector("[data-dz-size]").innerHTML = this.filesize(file.size); + _ref = file.previewElement.querySelectorAll("[data-dz-name]"); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + node = _ref[_i]; + node.textContent = file.name; + } + _ref1 = file.previewElement.querySelectorAll("[data-dz-size]"); + for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { + node = _ref1[_j]; + node.innerHTML = this.filesize(file.size); + } if (this.options.addRemoveLinks) { - file._removeLink = Dropzone.createElement("" + this.options.dictRemoveFile + ""); - file._removeLink.addEventListener("click", function(e) { + file._removeLink = Dropzone.createElement("" + this.options.dictRemoveFile + ""); + file.previewElement.appendChild(file._removeLink); + } + removeFileEvent = (function(_this) { + return function(e) { e.preventDefault(); e.stopPropagation(); if (file.status === Dropzone.UPLOADING) { - if (window.confirm(_this.options.dictCancelUploadConfirmation)) { + return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() { + return _this.removeFile(file); + }); + } else { + if (_this.options.dictRemoveFileConfirmation) { + return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() { + return _this.removeFile(file); + }); + } else { return _this.removeFile(file); } - } else { - return _this.removeFile(file); } - }); - return file.previewElement.appendChild(file._removeLink); + }; + })(this); + _ref2 = file.previewElement.querySelectorAll("[data-dz-remove]"); + _results = []; + for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { + removeLink = _ref2[_k]; + _results.push(removeLink.addEventListener("click", removeFileEvent)); } + return _results; }, removedfile: function(file) { var _ref; - return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0; + if ((_ref = file.previewElement) != null) { + _ref.parentNode.removeChild(file.previewElement); + } + return this._updateMaxFilesReachedClass(); }, thumbnail: function(file, dataUrl) { - var thumbnailElement; + var thumbnailElement, _i, _len, _ref, _results; file.previewElement.classList.remove("dz-file-preview"); file.previewElement.classList.add("dz-image-preview"); - thumbnailElement = file.previewElement.querySelector("[data-dz-thumbnail]"); - thumbnailElement.alt = file.name; - return thumbnailElement.src = dataUrl; + _ref = file.previewElement.querySelectorAll("[data-dz-thumbnail]"); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + thumbnailElement = _ref[_i]; + thumbnailElement.alt = file.name; + _results.push(thumbnailElement.src = dataUrl); + } + return _results; }, error: function(file, message) { + var node, _i, _len, _ref, _results; file.previewElement.classList.add("dz-error"); - return file.previewElement.querySelector("[data-dz-errormessage]").textContent = message; + if (typeof message !== "String" && message.error) { + message = message.error; + } + _ref = file.previewElement.querySelectorAll("[data-dz-errormessage]"); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + node = _ref[_i]; + _results.push(node.textContent = message); + } + return _results; }, + errormultiple: noop, processing: function(file) { file.previewElement.classList.add("dz-processing"); if (file._removeLink) { @@ -574,7 +495,14 @@ }, processingmultiple: noop, uploadprogress: function(file, progress, bytesSent) { - return file.previewElement.querySelector("[data-dz-uploadprogress]").style.width = "" + progress + "%"; + var node, _i, _len, _ref, _results; + _ref = file.previewElement.querySelectorAll("[data-dz-uploadprogress]"); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + node = _ref[_i]; + _results.push(node.style.width = "" + progress + "%"); + } + return _results; }, totaluploadprogress: noop, sending: noop, @@ -593,6 +521,8 @@ } }, completemultiple: noop, + maxfilesexceeded: noop, + maxfilesreached: noop, previewTemplate: "
\n
\n
\n
\n \n
\n
\n
\n
\n
\n
" }; @@ -627,11 +557,14 @@ throw new Error("Dropzone already attached."); } Dropzone.instances.push(this); - element.dropzone = this; + this.element.dropzone = this; elementOptions = (_ref = Dropzone.optionsForElement(this.element)) != null ? _ref : {}; this.options = extend({}, this.defaultOptions, elementOptions, options != null ? options : {}); + if (this.options.forceFallback || !Dropzone.isBrowserSupported()) { + return this.options.fallback.call(this); + } if (this.options.url == null) { - this.options.url = this.element.action; + this.options.url = this.element.getAttribute("action"); } if (!this.options.url) { throw new Error("No URL provided."); @@ -644,9 +577,6 @@ delete this.options.acceptedMimeTypes; } this.options.method = this.options.method.toUpperCase(); - if (this.options.forceFallback || !Dropzone.isBrowserSupported()) { - return this.options.fallback.call(this); - } if ((fallback = this.getExistingFallback()) && fallback.parentNode) { fallback.parentNode.removeChild(fallback); } @@ -718,8 +648,7 @@ }; Dropzone.prototype.init = function() { - var eventName, noPropagation, setupHiddenFileInput, _i, _len, _ref, _ref1, - _this = this; + var eventName, noPropagation, setupHiddenFileInput, _i, _len, _ref, _ref1; if (this.element.tagName === "form") { this.element.setAttribute("enctype", "multipart/form-data"); } @@ -727,35 +656,40 @@ this.element.appendChild(Dropzone.createElement("
" + this.options.dictDefaultMessage + "
")); } if (this.clickableElements.length) { - setupHiddenFileInput = function() { - if (_this.hiddenFileInput) { - document.body.removeChild(_this.hiddenFileInput); - } - _this.hiddenFileInput = document.createElement("input"); - _this.hiddenFileInput.setAttribute("type", "file"); - if (_this.options.uploadMultiple) { - _this.hiddenFileInput.setAttribute("multiple", "multiple"); - } - if (_this.options.acceptedFiles != null) { - _this.hiddenFileInput.setAttribute("accept", _this.options.acceptedFiles); - } - _this.hiddenFileInput.style.visibility = "hidden"; - _this.hiddenFileInput.style.position = "absolute"; - _this.hiddenFileInput.style.top = "0"; - _this.hiddenFileInput.style.left = "0"; - _this.hiddenFileInput.style.height = "0"; - _this.hiddenFileInput.style.width = "0"; - document.body.appendChild(_this.hiddenFileInput); - return _this.hiddenFileInput.addEventListener("change", function() { - var files; - files = _this.hiddenFileInput.files; - if (files.length) { - _this.emit("selectedfiles", files); - _this.handleFiles(files); + setupHiddenFileInput = (function(_this) { + return function() { + if (_this.hiddenFileInput) { + document.body.removeChild(_this.hiddenFileInput); } - return setupHiddenFileInput(); - }); - }; + _this.hiddenFileInput = document.createElement("input"); + _this.hiddenFileInput.setAttribute("type", "file"); + if ((_this.options.maxFiles == null) || _this.options.maxFiles > 1) { + _this.hiddenFileInput.setAttribute("multiple", "multiple"); + } + _this.hiddenFileInput.className = "dz-hidden-input"; + if (_this.options.acceptedFiles != null) { + _this.hiddenFileInput.setAttribute("accept", _this.options.acceptedFiles); + } + _this.hiddenFileInput.style.visibility = "hidden"; + _this.hiddenFileInput.style.position = "absolute"; + _this.hiddenFileInput.style.top = "0"; + _this.hiddenFileInput.style.left = "0"; + _this.hiddenFileInput.style.height = "0"; + _this.hiddenFileInput.style.width = "0"; + document.body.appendChild(_this.hiddenFileInput); + return _this.hiddenFileInput.addEventListener("change", function() { + var file, files, _i, _len; + files = _this.hiddenFileInput.files; + if (files.length) { + for (_i = 0, _len = files.length; _i < _len; _i++) { + file = files[_i]; + _this.addFile(file); + } + } + return setupHiddenFileInput(); + }); + }; + })(this); setupHiddenFileInput(); } this.URL = (_ref = window.URL) != null ? _ref : window.webkitURL; @@ -764,15 +698,30 @@ eventName = _ref1[_i]; this.on(eventName, this.options[eventName]); } - this.on("uploadprogress", function() { - return _this.updateTotalUploadProgress(); - }); - this.on("removedfile", function() { - return _this.updateTotalUploadProgress(); - }); - this.on("canceled", function(file) { - return _this.emit("complete", file); - }); + this.on("uploadprogress", (function(_this) { + return function() { + return _this.updateTotalUploadProgress(); + }; + })(this)); + this.on("removedfile", (function(_this) { + return function() { + return _this.updateTotalUploadProgress(); + }; + })(this)); + this.on("canceled", (function(_this) { + return function(file) { + return _this.emit("complete", file); + }; + })(this)); + this.on("complete", (function(_this) { + return function(file) { + if (_this.getUploadingFiles().length === 0 && _this.getQueuedFiles().length === 0) { + return setTimeout((function() { + return _this.emit("queuecomplete"); + }), 0); + } + }; + })(this)); noPropagation = function(e) { e.stopPropagation(); if (e.preventDefault) { @@ -785,43 +734,61 @@ { element: this.element, events: { - "dragstart": function(e) { - return _this.emit("dragstart", e); - }, - "dragenter": function(e) { - noPropagation(e); - return _this.emit("dragenter", e); - }, - "dragover": function(e) { - noPropagation(e); - return _this.emit("dragover", e); - }, - "dragleave": function(e) { - return _this.emit("dragleave", e); - }, - "drop": function(e) { - noPropagation(e); - _this.drop(e); - return _this.emit("drop", e); - }, - "dragend": function(e) { - return _this.emit("dragend", e); - } + "dragstart": (function(_this) { + return function(e) { + return _this.emit("dragstart", e); + }; + })(this), + "dragenter": (function(_this) { + return function(e) { + noPropagation(e); + return _this.emit("dragenter", e); + }; + })(this), + "dragover": (function(_this) { + return function(e) { + var efct; + try { + efct = e.dataTransfer.effectAllowed; + } catch (_error) {} + e.dataTransfer.dropEffect = 'move' === efct || 'linkMove' === efct ? 'move' : 'copy'; + noPropagation(e); + return _this.emit("dragover", e); + }; + })(this), + "dragleave": (function(_this) { + return function(e) { + return _this.emit("dragleave", e); + }; + })(this), + "drop": (function(_this) { + return function(e) { + noPropagation(e); + return _this.drop(e); + }; + })(this), + "dragend": (function(_this) { + return function(e) { + return _this.emit("dragend", e); + }; + })(this) } } ]; - this.clickableElements.forEach(function(clickableElement) { - return _this.listeners.push({ - element: clickableElement, - events: { - "click": function(evt) { - if ((clickableElement !== _this.element) || (evt.target === _this.element || Dropzone.elementInside(evt.target, _this.element.querySelector(".dz-message")))) { - return _this.hiddenFileInput.click(); + this.clickableElements.forEach((function(_this) { + return function(clickableElement) { + return _this.listeners.push({ + element: clickableElement, + events: { + "click": function(evt) { + if ((clickableElement !== _this.element) || (evt.target === _this.element || Dropzone.elementInside(evt.target, _this.element.querySelector(".dz-message")))) { + return _this.hiddenFileInput.click(); + } } } - } - }); - }); + }); + }; + })(this)); this.enable(); return this.options.init.call(this); }; @@ -834,7 +801,8 @@ this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput); this.hiddenFileInput = null; } - return delete this.element.dropzone; + delete this.element.dropzone; + return Dropzone.instances.splice(Dropzone.instances.indexOf(this), 1); }; Dropzone.prototype.updateTotalUploadProgress = function() { @@ -865,7 +833,7 @@ if (this.options.dictFallbackText) { fieldsString += "

" + this.options.dictFallbackText + "

"; } - fieldsString += "
"; + fieldsString += "
"; fields = Dropzone.createElement(fieldsString); if (this.element.tagName !== "FORM") { form = Dropzone.createElement("
"); @@ -961,18 +929,18 @@ Dropzone.prototype.filesize = function(size) { var string; - if (size >= 100000000000) { - size = size / 100000000000; - string = "TB"; - } else if (size >= 100000000) { - size = size / 100000000; - string = "GB"; - } else if (size >= 100000) { - size = size / 100000; - string = "MB"; - } else if (size >= 100) { - size = size / 100; - string = "KB"; + if (size >= 1024 * 1024 * 1024 * 1024 / 10) { + size = size / (1024 * 1024 * 1024 * 1024 / 10); + string = "TiB"; + } else if (size >= 1024 * 1024 * 1024 / 10) { + size = size / (1024 * 1024 * 1024 / 10); + string = "GiB"; + } else if (size >= 1024 * 1024 / 10) { + size = size / (1024 * 1024 / 10); + string = "MiB"; + } else if (size >= 1024 / 10) { + size = size / (1024 / 10); + string = "KiB"; } else { size = size * 10; string = "b"; @@ -980,23 +948,46 @@ return "" + (Math.round(size) / 10) + " " + string; }; + Dropzone.prototype._updateMaxFilesReachedClass = function() { + if ((this.options.maxFiles != null) && this.getAcceptedFiles().length >= this.options.maxFiles) { + if (this.getAcceptedFiles().length === this.options.maxFiles) { + this.emit('maxfilesreached', this.files); + } + return this.element.classList.add("dz-max-files-reached"); + } else { + return this.element.classList.remove("dz-max-files-reached"); + } + }; + Dropzone.prototype.drop = function(e) { var files, items; if (!e.dataTransfer) { return; } + this.emit("drop", e); files = e.dataTransfer.files; - this.emit("selectedfiles", files); if (files.length) { items = e.dataTransfer.items; - if (items && items.length && ((items[0].webkitGetAsEntry != null) || (items[0].getAsEntry != null))) { - this.handleItems(items); + if (items && items.length && (items[0].webkitGetAsEntry != null)) { + this._addFilesFromItems(items); } else { this.handleFiles(files); } } }; + Dropzone.prototype.paste = function(e) { + var items, _ref; + if ((e != null ? (_ref = e.clipboardData) != null ? _ref.items : void 0 : void 0) == null) { + return; + } + this.emit("paste", e); + items = e.clipboardData.items; + if (items.length) { + return this._addFilesFromItems(items); + } + }; + Dropzone.prototype.handleFiles = function(files) { var file, _i, _len, _results; _results = []; @@ -1007,21 +998,57 @@ return _results; }; - Dropzone.prototype.handleItems = function(items) { - var entry, item, _i, _len; + Dropzone.prototype._addFilesFromItems = function(items) { + var entry, item, _i, _len, _results; + _results = []; for (_i = 0, _len = items.length; _i < _len; _i++) { item = items[_i]; - if (item.webkitGetAsEntry != null) { - entry = item.webkitGetAsEntry(); + if ((item.webkitGetAsEntry != null) && (entry = item.webkitGetAsEntry())) { if (entry.isFile) { - this.addFile(item.getAsFile()); + _results.push(this.addFile(item.getAsFile())); } else if (entry.isDirectory) { - this.addDirectory(entry, entry.name); + _results.push(this._addFilesFromDirectory(entry, entry.name)); + } else { + _results.push(void 0); + } + } else if (item.getAsFile != null) { + if ((item.kind == null) || item.kind === "file") { + _results.push(this.addFile(item.getAsFile())); + } else { + _results.push(void 0); } } else { - this.addFile(item.getAsFile()); + _results.push(void 0); } } + return _results; + }; + + Dropzone.prototype._addFilesFromDirectory = function(directory, path) { + var dirReader, entriesReader; + dirReader = directory.createReader(); + entriesReader = (function(_this) { + return function(entries) { + var entry, _i, _len; + for (_i = 0, _len = entries.length; _i < _len; _i++) { + entry = entries[_i]; + if (entry.isFile) { + entry.file(function(file) { + if (_this.options.ignoreHiddenFiles && file.name.substring(0, 1) === '.') { + return; + } + file.fullPath = "" + path + "/" + file.name; + return _this.addFile(file); + }); + } else if (entry.isDirectory) { + _this._addFilesFromDirectory(entry, "" + path + "/" + entry.name); + } + } + }; + })(this); + return dirReader.readEntries(entriesReader, function(error) { + return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log(error) : void 0 : void 0; + }); }; Dropzone.prototype.accept = function(file, done) { @@ -1029,13 +1056,15 @@ return done(this.options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", this.options.maxFilesize)); } else if (!Dropzone.isValidFile(file, this.options.acceptedFiles)) { return done(this.options.dictInvalidFileType); + } else if ((this.options.maxFiles != null) && this.getAcceptedFiles().length >= this.options.maxFiles) { + done(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}", this.options.maxFiles)); + return this.emit("maxfilesexceeded", file); } else { return this.options.accept.call(this, file, done); } }; Dropzone.prototype.addFile = function(file) { - var _this = this; file.upload = { progress: 0, total: file.size, @@ -1044,18 +1073,18 @@ this.files.push(file); file.status = Dropzone.ADDED; this.emit("addedfile", file); - if (this.options.createImageThumbnails && file.type.match(/image.*/) && file.size <= this.options.maxThumbnailFilesize * 1024 * 1024) { - this.createThumbnail(file); - } - return this.accept(file, function(error) { - if (error) { - file.accepted = false; - return _this._errorProcessing([file], error); - } else { - file.accepted = true; - return _this.enqueueFile(file); - } - }); + this._enqueueThumbnail(file); + return this.accept(file, (function(_this) { + return function(error) { + if (error) { + file.accepted = false; + _this._errorProcessing([file], error); + } else { + _this.enqueueFile(file); + } + return _this._updateMaxFilesReachedClass(); + }; + })(this)); }; Dropzone.prototype.enqueueFiles = function(files) { @@ -1068,43 +1097,47 @@ }; Dropzone.prototype.enqueueFile = function(file) { - var _this = this; + file.accepted = true; if (file.status === Dropzone.ADDED) { file.status = Dropzone.QUEUED; if (this.options.autoProcessQueue) { - return setTimeout((function() { - return _this.processQueue(); - }), 1); + return setTimeout(((function(_this) { + return function() { + return _this.processQueue(); + }; + })(this)), 0); } } else { throw new Error("This file can't be queued because it has already been processed or was rejected."); } }; - Dropzone.prototype.addDirectory = function(entry, path) { - var dirReader, entriesReader, - _this = this; - dirReader = entry.createReader(); - entriesReader = function(entries) { - var _i, _len; - for (_i = 0, _len = entries.length; _i < _len; _i++) { - entry = entries[_i]; - if (entry.isFile) { - entry.file(function(file) { - if (_this.options.ignoreHiddenFiles && file.name.substring(0, 1) === '.') { - return; - } - file.fullPath = "" + path + "/" + file.name; - return _this.addFile(file); - }); - } else if (entry.isDirectory) { - _this.addDirectory(entry, "" + path + "/" + entry.name); - } - } - }; - return dirReader.readEntries(entriesReader, function(error) { - return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log(error) : void 0 : void 0; - }); + Dropzone.prototype._thumbnailQueue = []; + + Dropzone.prototype._processingThumbnail = false; + + Dropzone.prototype._enqueueThumbnail = function(file) { + if (this.options.createImageThumbnails && file.type.match(/image.*/) && file.size <= this.options.maxThumbnailFilesize * 1024 * 1024) { + this._thumbnailQueue.push(file); + return setTimeout(((function(_this) { + return function() { + return _this._processThumbnailQueue(); + }; + })(this)), 0); + } + }; + + Dropzone.prototype._processThumbnailQueue = function() { + if (this._processingThumbnail || this._thumbnailQueue.length === 0) { + return; + } + this._processingThumbnail = true; + return this.createThumbnail(this._thumbnailQueue.shift(), (function(_this) { + return function() { + _this._processingThumbnail = false; + return _this._processThumbnailQueue(); + }; + })(this)); }; Dropzone.prototype.removeFile = function(file) { @@ -1133,34 +1166,38 @@ return null; }; - Dropzone.prototype.createThumbnail = function(file) { - var fileReader, - _this = this; + Dropzone.prototype.createThumbnail = function(file, callback) { + var fileReader; fileReader = new FileReader; - fileReader.onload = function() { - var img; - img = new Image; - img.onload = function() { - var canvas, ctx, resizeInfo, thumbnail, _ref, _ref1, _ref2, _ref3; - file.width = img.width; - file.height = img.height; - resizeInfo = _this.options.resize.call(_this, file); - if (resizeInfo.trgWidth == null) { - resizeInfo.trgWidth = _this.options.thumbnailWidth; - } - if (resizeInfo.trgHeight == null) { - resizeInfo.trgHeight = _this.options.thumbnailHeight; - } - canvas = document.createElement("canvas"); - ctx = canvas.getContext("2d"); - canvas.width = resizeInfo.trgWidth; - canvas.height = resizeInfo.trgHeight; - ctx.drawImage(img, (_ref = resizeInfo.srcX) != null ? _ref : 0, (_ref1 = resizeInfo.srcY) != null ? _ref1 : 0, resizeInfo.srcWidth, resizeInfo.srcHeight, (_ref2 = resizeInfo.trgX) != null ? _ref2 : 0, (_ref3 = resizeInfo.trgY) != null ? _ref3 : 0, resizeInfo.trgWidth, resizeInfo.trgHeight); - thumbnail = canvas.toDataURL("image/png"); - return _this.emit("thumbnail", file, thumbnail); + fileReader.onload = (function(_this) { + return function() { + var img; + img = document.createElement("img"); + img.onload = function() { + var canvas, ctx, resizeInfo, thumbnail, _ref, _ref1, _ref2, _ref3; + file.width = img.width; + file.height = img.height; + resizeInfo = _this.options.resize.call(_this, file); + if (resizeInfo.trgWidth == null) { + resizeInfo.trgWidth = _this.options.thumbnailWidth; + } + if (resizeInfo.trgHeight == null) { + resizeInfo.trgHeight = _this.options.thumbnailHeight; + } + canvas = document.createElement("canvas"); + ctx = canvas.getContext("2d"); + canvas.width = resizeInfo.trgWidth; + canvas.height = resizeInfo.trgHeight; + drawImageIOSFix(ctx, img, (_ref = resizeInfo.srcX) != null ? _ref : 0, (_ref1 = resizeInfo.srcY) != null ? _ref1 : 0, resizeInfo.srcWidth, resizeInfo.srcHeight, (_ref2 = resizeInfo.trgX) != null ? _ref2 : 0, (_ref3 = resizeInfo.trgY) != null ? _ref3 : 0, resizeInfo.trgWidth, resizeInfo.trgHeight); + thumbnail = canvas.toDataURL("image/png"); + _this.emit("thumbnail", file, thumbnail); + if (callback != null) { + return callback(); + } + }; + return img.src = fileReader.result; }; - return img.src = fileReader.result; - }; + })(this); return fileReader.readAsDataURL(file); }; @@ -1169,12 +1206,15 @@ parallelUploads = this.options.parallelUploads; processingLength = this.getUploadingFiles().length; i = processingLength; + if (processingLength >= parallelUploads) { + return; + } queuedFiles = this.getQueuedFiles(); if (!(queuedFiles.length > 0)) { return; } if (this.options.uploadMultiple) { - return this.processFiles(queuedFiles.slice(0, parallelUploads)); + return this.processFiles(queuedFiles.slice(0, parallelUploads - processingLength)); } else { while (i < parallelUploads) { if (!queuedFiles.length) { @@ -1253,8 +1293,7 @@ }; Dropzone.prototype.uploadFiles = function(files) { - var file, formData, handleError, header, headers, input, inputName, inputType, key, name, progressObj, response, updateProgress, value, xhr, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3, - _this = this; + var file, formData, handleError, headerName, headerValue, headers, input, inputName, inputType, key, option, progressObj, response, updateProgress, value, xhr, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m, _ref, _ref1, _ref2, _ref3, _ref4; xhr = new XMLHttpRequest(); for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; @@ -1263,79 +1302,87 @@ xhr.open(this.options.method, this.options.url, true); xhr.withCredentials = !!this.options.withCredentials; response = null; - handleError = function() { - var _j, _len1, _results; - _results = []; - for (_j = 0, _len1 = files.length; _j < _len1; _j++) { - file = files[_j]; - _results.push(_this._errorProcessing(files, response || _this.options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr)); - } - return _results; - }; - updateProgress = function(e) { - var allFilesFinished, progress, _j, _k, _l, _len1, _len2, _len3, _results; - if (e != null) { - progress = 100 * e.loaded / e.total; + handleError = (function(_this) { + return function() { + var _j, _len1, _results; + _results = []; for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; - file.upload = { - progress: progress, - total: e.total, - bytesSent: e.loaded - }; + _results.push(_this._errorProcessing(files, response || _this.options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr)); } - } else { - allFilesFinished = true; - progress = 100; - for (_k = 0, _len2 = files.length; _k < _len2; _k++) { - file = files[_k]; - if (!(file.upload.progress === 100 && file.upload.bytesSent === file.upload.total)) { - allFilesFinished = false; + return _results; + }; + })(this); + updateProgress = (function(_this) { + return function(e) { + var allFilesFinished, progress, _j, _k, _l, _len1, _len2, _len3, _results; + if (e != null) { + progress = 100 * e.loaded / e.total; + for (_j = 0, _len1 = files.length; _j < _len1; _j++) { + file = files[_j]; + file.upload = { + progress: progress, + total: e.total, + bytesSent: e.loaded + }; } - file.upload.progress = progress; - file.upload.bytesSent = file.upload.total; + } else { + allFilesFinished = true; + progress = 100; + for (_k = 0, _len2 = files.length; _k < _len2; _k++) { + file = files[_k]; + if (!(file.upload.progress === 100 && file.upload.bytesSent === file.upload.total)) { + allFilesFinished = false; + } + file.upload.progress = progress; + file.upload.bytesSent = file.upload.total; + } + if (allFilesFinished) { + return; + } } - if (allFilesFinished) { + _results = []; + for (_l = 0, _len3 = files.length; _l < _len3; _l++) { + file = files[_l]; + _results.push(_this.emit("uploadprogress", file, progress, file.upload.bytesSent)); + } + return _results; + }; + })(this); + xhr.onload = (function(_this) { + return function(e) { + var _ref; + if (files[0].status === Dropzone.CANCELED) { return; } - } - _results = []; - for (_l = 0, _len3 = files.length; _l < _len3; _l++) { - file = files[_l]; - _results.push(_this.emit("uploadprogress", file, progress, file.upload.bytesSent)); - } - return _results; - }; - xhr.onload = function(e) { - var _ref; - if (files[0].status === Dropzone.CANCELED) { - return; - } - if (xhr.readyState !== 4) { - return; - } - response = xhr.responseText; - if (xhr.getResponseHeader("content-type") && ~xhr.getResponseHeader("content-type").indexOf("application/json")) { - try { - response = JSON.parse(response); - } catch (_error) { - e = _error; - response = "Invalid JSON response from server."; + if (xhr.readyState !== 4) { + return; } - } - updateProgress(); - if (!((200 <= (_ref = xhr.status) && _ref < 300))) { + response = xhr.responseText; + if (xhr.getResponseHeader("content-type") && ~xhr.getResponseHeader("content-type").indexOf("application/json")) { + try { + response = JSON.parse(response); + } catch (_error) { + e = _error; + response = "Invalid JSON response from server."; + } + } + updateProgress(); + if (!((200 <= (_ref = xhr.status) && _ref < 300))) { + return handleError(); + } else { + return _this._finished(files, response, e); + } + }; + })(this); + xhr.onerror = (function(_this) { + return function() { + if (files[0].status === Dropzone.CANCELED) { + return; + } return handleError(); - } else { - return _this._finished(files, response, e); - } - }; - xhr.onerror = function() { - if (files[0].status === Dropzone.CANCELED) { - return; - } - return handleError(); - }; + }; + })(this); progressObj = (_ref = xhr.upload) != null ? _ref : xhr; progressObj.onprogress = updateProgress; headers = { @@ -1346,9 +1393,9 @@ if (this.options.headers) { extend(headers, this.options.headers); } - for (header in headers) { - name = headers[header]; - xhr.setRequestHeader(header, name); + for (headerName in headers) { + headerValue = headers[headerName]; + xhr.setRequestHeader(headerName, headerValue); } formData = new FormData(); if (this.options.params) { @@ -1371,13 +1418,21 @@ input = _ref2[_k]; inputName = input.getAttribute("name"); inputType = input.getAttribute("type"); - if (!inputType || ((_ref3 = inputType.toLowerCase()) !== "checkbox" && _ref3 !== "radio") || input.checked) { + if (input.tagName === "SELECT" && input.hasAttribute("multiple")) { + _ref3 = input.options; + for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) { + option = _ref3[_l]; + if (option.selected) { + formData.append(inputName, option.value); + } + } + } else if (!inputType || ((_ref4 = inputType.toLowerCase()) !== "checkbox" && _ref4 !== "radio") || input.checked) { formData.append(inputName, input.value); } } } - for (_l = 0, _len3 = files.length; _l < _len3; _l++) { - file = files[_l]; + for (_m = 0, _len4 = files.length; _m < _len4; _m++) { + file = files[_m]; formData.append("" + this.options.paramName + (this.options.uploadMultiple ? "[]" : ""), file, file.name); } return xhr.send(formData); @@ -1421,13 +1476,13 @@ })(Em); - Dropzone.version = "3.6.1"; + Dropzone.version = "3.8.5"; Dropzone.options = {}; Dropzone.optionsForElement = function(element) { - if (element.id) { - return Dropzone.options[camelize(element.id)]; + if (element.getAttribute("id")) { + return Dropzone.options[camelize(element.getAttribute("id"))]; } else { return void 0; } @@ -1449,9 +1504,6 @@ Dropzone.discover = function() { var checkElements, dropzone, dropzones, _i, _len, _results; - if (!Dropzone.autoDiscover) { - return; - } if (document.querySelectorAll) { dropzones = document.querySelectorAll(".dropzone"); } else { @@ -1522,7 +1574,7 @@ camelize = function(str) { return str.replace(/[\-_](\w)/g, function(match) { - return match[1].toUpperCase(); + return match.charAt(1).toUpperCase(); }); }; @@ -1587,6 +1639,14 @@ return elements; }; + Dropzone.confirm = function(question, accepted, rejected) { + if (window.confirm(question)) { + return accepted(); + } else if (rejected != null) { + return rejected(); + } + }; + Dropzone.isValidFile = function(file, acceptedFiles) { var baseMimeType, mimeType, validType, _i, _len; if (!acceptedFiles) { @@ -1599,7 +1659,7 @@ validType = acceptedFiles[_i]; validType = validType.trim(); if (validType.charAt(0) === ".") { - if (file.name.indexOf(validType, file.name.length - validType.length) !== -1) { + if (file.name.toLowerCase().indexOf(validType.toLowerCase(), file.name.length - validType.length) !== -1) { return true; } } else if (/\/\*$/.test(validType)) { @@ -1645,20 +1705,64 @@ Dropzone.SUCCESS = "success"; - /* - # contentloaded.js - # - # Author: Diego Perini (diego.perini at gmail.com) - # Summary: cross-browser wrapper for DOMContentLoaded - # Updated: 20101020 - # License: MIT - # Version: 1.2 - # - # URL: - # http://javascript.nwbox.com/ContentLoaded/ - # http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE - */ + /* + + Bugfix for iOS 6 and 7 + Source: http://stackoverflow.com/questions/11929099/html5-canvas-drawimage-ratio-bug-ios + based on the work of https://github.com/stomita/ios-imagefile-megapixel + */ + + detectVerticalSquash = function(img) { + var alpha, canvas, ctx, data, ey, ih, iw, py, ratio, sy; + iw = img.naturalWidth; + ih = img.naturalHeight; + canvas = document.createElement("canvas"); + canvas.width = 1; + canvas.height = ih; + ctx = canvas.getContext("2d"); + ctx.drawImage(img, 0, 0); + data = ctx.getImageData(0, 0, 1, ih).data; + sy = 0; + ey = ih; + py = ih; + while (py > sy) { + alpha = data[(py - 1) * 4 + 3]; + if (alpha === 0) { + ey = py; + } else { + sy = py; + } + py = (ey + sy) >> 1; + } + ratio = py / ih; + if (ratio === 0) { + return 1; + } else { + return ratio; + } + }; + + drawImageIOSFix = function(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) { + var vertSquashRatio; + vertSquashRatio = detectVerticalSquash(img); + return ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio); + }; + + + /* + * contentloaded.js + * + * Author: Diego Perini (diego.perini at gmail.com) + * Summary: cross-browser wrapper for DOMContentLoaded + * Updated: 20101020 + * License: MIT + * Version: 1.2 + * + * URL: + * http://javascript.nwbox.com/ContentLoaded/ + * http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE + */ contentLoaded = function(win, fn) { var add, doc, done, init, poll, pre, rem, root, top; @@ -1704,18 +1808,23 @@ } }; - contentLoaded(window, Dropzone.discover); + Dropzone._autoDiscoverFunction = function() { + if (Dropzone.autoDiscover) { + return Dropzone.discover(); + } + }; + + contentLoaded(window, Dropzone._autoDiscoverFunction); }).call(this); }); -require.alias("component-emitter/index.js", "dropzone/deps/emitter/index.js"); -require.alias("component-emitter/index.js", "emitter/index.js"); if (typeof exports == "object") { module.exports = require("dropzone"); } else if (typeof define == "function" && define.amd) { - define(function(){ return require("dropzone"); }); + define([], function(){ return require("dropzone"); }); } else { this["Dropzone"] = require("dropzone"); -}})(); \ No newline at end of file +} +})()