/
uploads.js.coffee.erb
72 lines (48 loc) · 2.52 KB
/
uploads.js.coffee.erb
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
jQuery ->
uploaderHost = "http://#{$('#uploader').data('s3-bucket')}.s3.amazonaws.com"
xhrUploadProgressSupported = () ->
xhr = new XMLHttpRequest()
xhr && ('upload' of xhr) && ('onprogress' of xhr.upload)
# Can only track progress if size property is present on files.
progressSupported = xhrUploadProgressSupported()
$('#uploading_files').on 'click', '.uploading_file .remove_link', (e) ->
uuid = $(this).parent().data('uuid')
$(this).parent().remove()
$('#uploader iframe')[0].contentWindow.postMessage(JSON.stringify({ eventType: 'abort upload', uuid: uuid }), uploaderHost);
$(window).on "message", (event) ->
event = event.originalEvent
if event.origin != uploaderHost
return
data = JSON.parse(event.data)
eventType = data.eventType
delete data.eventType
switch eventType
when 'upload done'
$(".uploading_file[data-uuid=#{data.uuid}]").remove()
$.ajax $('#uploader iframe').data('create-resource-url'),
type: 'POST',
data: data,
dataType: 'text',
success: (upload_id) ->
wrapper = $('<div class="wrapper"></div>')
img = $('<img class="thumb">')
remove_btn = $("<img src='<%= asset_path('delete.png') %>' class='delete' />")
remove_btn.click () ->
$(this).parent().fadeOut(() -> $(this).remove())
img_id = $('<input type="hidden" name="uploads[]" />')
img.attr('src', "#{uploaderHost}/#{data.s3_key}/#{data.file_name}")
img.attr('data-img-id', upload_id)
img_id.val(upload_id)
wrapper.append(img).append(img_id).append(remove_btn)
$('#uploader').append(wrapper)
when 'add upload'
if progressSupported
uploadPercent = "<br/><progress value='0' max='100' class='upload_progress_bar'>0</progress> <span class='upload_percentage'>0</span> %";
$('#uploading_files').append("<p class='uploading_file'>#{data.file_name + uploadPercent} <a href='#' class='remove_link'>X</a></p>");
else
$('#uploading_files').append("<p class='uploading_file'>#{data.file_name}<br/><img src='<%= asset_path('uploading.gif') %>'/></p>");
$('.uploading_file').last().attr 'data-uuid', data.uuid
when 'upload progress'
if progressSupported
$(".uploading_file[data-uuid=#{data.uuid}]").find('.upload_percentage').html(data.progress)
$(".uploading_file[data-uuid=#{data.uuid}]").find('.upload_progress_bar').val(data.progress)