-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
dropzone.coffee
421 lines (303 loc) · 12.3 KB
/
dropzone.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
$ = ender
$.ender
dropzone: (options) ->
for element in @
new Dropzone element, options
, true # Should be added to the internal chain
$.domReady -> $(".dropzone").dropzone()
bean = require "bean"
noOp = ->
class Dropzone
version: "1.0.0"
###
This is a list of all available events you can register on a dropzone object.
You can register an event handler like this:
var bean = require("bean");
bean.add(dropzone, "dragEnter", function() { });
###
events: [
"fallback"
"drop"
"dragstart"
"dragend"
"dragenter"
"dragover"
"dragleave"
"addedfile"
"thumbnail"
"error"
"processingfile"
"uploadprogress"
"finished"
]
defaultOptions =
url: null
parallelUploads: 2
maxFilesize: 256 # in MB
paramName: "file" # The name of the file param that gets transferred.
createImageThumbnails: true
maxThumbnailFilesize: 2 # in MB. When the filename exeeds this limit, the thumbnail will not be generated.
thumbnailWidth: 100
thumbnailHeight: 100
# If false the file does not get processed.
accept: (file) -> true
###
Those functions register themselves to the events on init.
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.
###
# Called when the browser does not support drag and drop
fallback: ->
@element.addClass "browser-not-supported"
@element.find(".message span").html "Your browser does not support drag'n'drop file uploads."
@element.append """<p>Sadly your dusty browser does not support nice drag'n'drop file uploads.<br />Please use the fallback form below to upload your files like in the olden days.</p>"""
@element.append @getFallbackForm()
# Those are self explanatory and simply concern the DragnDrop.
drop: (e) ->
@element.removeClass "drag-hover"
@element.addClass "started"
dragstart: (e) ->
dragend: (e) -> @element.removeClass "drag-hover"
dragenter: (e) -> @element.addClass "drag-hover"
dragover: (e) -> @element.addClass "drag-hover"
dragleave: (e) -> @element.removeClass "drag-hover"
# Called when a file is added to the queue
# Receives `file`
addedfile: (file) ->
file.previewTemplate = $ @options.previewTemplate
@element.append file.previewTemplate
file.previewTemplate.find(".filename span").text file.name
file.previewTemplate.find(".details").append $("""<div class="size">#{@filesize file.size}</div>""")
# Called when a thumbnail has been generated
# Receives `file` and `dataUrl`
thumbnail: (file, dataUrl) ->
file.previewTemplate
.removeClass("file-preview")
.addClass("image-preview")
file.previewTemplate.find(".details").append $("""<img alt="#{file.name}" src="#{dataUrl}"/>""")
# Called whenever an error occures
# Receives `file` and `message`
error: (file, message) ->
file.previewTemplate.addClass "error"
file.previewTemplate.find(".error-message span").text message
# Called when a file gets processed
# Receives `file`
processingfile: (file) ->
file.previewTemplate.addClass "processing"
# Called whenever the upload progress gets upadted.
# You can be sure that this will be called with the percentage 100% when the file is finished uploading.
# Receives `file` and `progress` (percentage)
uploadprogress: (file, progress) ->
file.previewTemplate.find(".progress .upload").css { width: "#{progress}%" }
# When the complete upload is finished
# Receives `file`
finished: (file) ->
file.previewTemplate.addClass "success"
# This template will be chosen when a new file is dropped.
previewTemplate: """
<div class="preview file-preview">
<div class="details"></div>
<div class="progress"><span class="load"></span><span class="upload"></span></div>
<div class="success-mark"><span>✔</span></div>
<div class="error-mark"><span>✘</span></div>
<div class="error-message"><span></span></div>
<div class="filename"><span></span></div>
</div>
"""
defaultOptions.previewTemplate = defaultOptions.previewTemplate.replace /\n*/g, ""
constructor: (element, options) ->
@element = $ element
throw new Error "You can only instantiate dropzone on a single element." if @element.length != 1
throw new Error "Dropzone already attached." if @element.data("dropzone")
@element.data "dropzone", @
@elementTagName = @element.get(0).tagName
extend = (target, objects...) ->
for object in objects
target[key] = val for key, val of object
target
@options = extend { }, defaultOptions, options ? { }
@options.url = @element.attr "action" unless @options.url?
@init()
init: ->
if @elementTagName == "form" and @element.attr("enctype") != "multipart/form-data"
@element.attr "enctype", "multipart/form-data"
if @element.find(".message").length == 0
@element.append $ """<div class="message"><span>Drop files here to upload</span></div>"""
unless window.File and window.FileReader and window.FileList and window.Blob and window.FormData
@options.fallback.call this
return
@files = [] # All files
@files.queue = [] # The files that still have to be processed
@files.processing = [] # The files currently processed
@URL = window.URL ? window.webkitURL
@setupEventListeners()
# Returns a form that can be used as fallback if the browser does not support DragnDrop
#
# If the dropzone is already a form, only the input field and button are returned. Otherwise a complete form element is provided.
getFallbackForm: ->
fields = $ """<div class="fallback-elements"><input type="file" name="newFiles" multiple="multiple" /><button type="submit">Upload!</button></div>"""
if @elementTagName isnt "FORM"
fields = $("""<form action="#{@options.url}" enctype="multipart/form-data" method="post"></form>""").append fields
fields
setupEventListeners: ->
# First setup all event listeners on the dropzone object itself.
bean.add @, eventName, @options[eventName] for eventName in @events
noPropagation = (e) ->
e.stopPropagation()
e.preventDefault()
@element.on "dragstart", (e) =>
bean.fire @, "dragstart", e
@element.on "dragenter", (e) =>
noPropagation e
bean.fire @, "dragenter", e
@element.on "dragover", (e) =>
noPropagation e
bean.fire @, "dragover", e
@element.on "dragleave", (e) =>
bean.fire @, "dragleave", e
@element.on "drop", (e) =>
noPropagation e
@drop e
bean.fire @, "drop", e
@element.on "dragend", (e) =>
bean.fire @, "dragend", e
# Returns a nicely formatted filesize
filesize: (size) ->
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"
else
size = size * 10
string = "by"
"#{Math.round(size)/10} #{string}"
drop: (e) ->
return unless e.dataTransfer
files = e.dataTransfer.files
@handleFiles files if files.length
handleFiles: (files) ->
@addFile file for file in files when @accept file
@processQueue()
accept: (file) ->
# Add file size check here.
@options.accept.call this, file
addFile: (file) ->
@files.push file
@files.queue.push file
bean.fire @, "addedfile", file
@createThumbnail file if @options.createImageThumbnails and file.type.match(/image.*/) and file.size <= @options.maxThumbnailFilesize * 1024 * 1024
createThumbnail: (file) ->
img = new Image()
blobUrl = @URL.createObjectURL file
img.onerror = img.onabort = ->
@URL.revokeObjectURL blobUrl
img = null
img.onload = =>
canvas = document.createElement("canvas")
ctx = canvas.getContext("2d")
srcX = 0
srcY = 0
srcWidth = img.width
srcHeight = img.height
canvas.width = @options.thumbnailWidth
canvas.height = @options.thumbnailHeight
trgX = 0
trgY = 0
trgWidth = canvas.width
trgHeight = canvas.height
srcRatio = img.width / img.height
trgRatio = canvas.width / canvas.height
if img.height < canvas.height or img.width < canvas.width
# This image is smaller than the canvas
trgHeight = srcHeight
trgWidth = srcWidth
else
# Image is bigger and needs rescaling
if srcRatio > trgRatio
srcHeight = img.height
srcWidth = srcHeight * trgRatio
else
srcWidth = img.width
srcHeight = srcWidth / trgRatio
srcX = (img.width - srcWidth) / 2
srcY = (img.height - srcHeight) / 2
trgY = (canvas.height - trgHeight) / 2
trgX = (canvas.width - trgWidth) / 2
ctx.drawImage img, srcX, srcY, srcWidth, srcHeight, trgX, trgY, trgWidth, trgHeight
thumbnail = canvas.toDataURL("image/png")
bean.fire @, "thumbnail", [ file, thumbnail ]
@URL.revokeObjectURL blobUrl
img = null
img.src = blobUrl
# Goes through the qeue and processes files if there aren't too many already.
processQueue: ->
parallelUploads = @options.parallelUploads
processingLength = @files.processing.length
i = processingLength
while i < parallelUploads
return unless @files.queue.length # Nothing left to process
@processFile @files.queue.shift()
i++
# Loads the file, then calls finishedLoading()
processFile: (file) ->
fileReader = new FileReader()
@files.processing.push file
bean.fire @, "processingfile", file
if file.size > @options.maxFilesize * 1024 * 1024
@errorProcessing file, "File is too big (" + (Math.round(file.size / 1024 / 10.24) / 100) + "MB). Max filesize: " + @options.maxFilesize + "MB"
else
@uploadFile file
uploadFile: (file) ->
xhr = new XMLHttpRequest()
formData = new FormData()
formData.append @options.paramName, file
if @elementTagName = "FORM"
# Take care of other input elements
for inputElement in @element.find "input, textarea, select, button"
input = $ inputElement
inputName = input.attr("name")
if !input.attr("type") or input.attr("type").toLowerCase() != "checkbox" or inputElement.checked
formData.append input.attr("name"), input.val()
xhr.open "POST", @options.url, true
handleError = =>
@errorProcessing file, xhr.responseText || "Server responded with #{xhr.status} code."
xhr.onload = (e) =>
if xhr.status isnt 200
handleError()
else
bean.fire @, "uploadprogress", [ file, 100 ]
response = xhr.responseText
if ~xhr.getResponseHeader("content-type").indexOf "application/json" then response = JSON.parse response
@finished file, response, e
xhr.onerror = =>
handleError()
# Some browsers do not have the .upload property
progressObj = xhr.upload ? xhr
progressObj.onprogress = (e) =>
bean.fire @, "uploadprogress", [ file, Math.max(0, Math.min(100, (e.loaded / e.total) * 100)) ]
xhr.setRequestHeader "Accept", "application/json"
xhr.setRequestHeader "Cache-Control", "no-cache"
xhr.setRequestHeader "X-Requested-With", "XMLHttpRequest"
xhr.setRequestHeader "X-File-Name", file.name
xhr.send formData
# Called internally when processing is finished.
# Individual callbacks have to be called in the appropriate sections.
finished: (file, responseText, e) ->
@files.processing = without(@files.processing, file)
bean.fire @, "finished", [ file, responseText, e ]
@processQueue()
# Called internally when processing is finished.
# Individual callbacks have to be called in the appropriate sections.
errorProcessing: (file, message) ->
@files.processing = without(@files.processing, file)
bean.fire @, "error", [ file, message ]
@processQueue()
without = (list, rejectedItem) -> item for item in list when item isnt rejectedItem