/
app.js
105 lines (89 loc) · 2.8 KB
/
app.js
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
const singleFileUpload = (fileInput) => {
const imagePreview = document.getElementById(fileInput.dataset.previewElement)
const formGroup = fileInput.parentNode
formGroup.removeChild(fileInput)
const uppy = fileUpload(fileInput)
uppy
.use(Uppy.FileInput, {
target: formGroup,
locale: { strings: { chooseFiles: 'Choose file' } },
})
.use(Uppy.Informer, {
target: formGroup,
})
.use(Uppy.ProgressBar, {
target: imagePreview.parentNode,
})
.use(Uppy.ThumbnailGenerator, {
thumbnailWidth: 600,
})
uppy.on('upload-success', (file, response) => {
// set hidden field value to the uploaded file data so that it's submitted with the form as the attachment
const hiddenInput = document.getElementById(fileInput.dataset.uploadResultElement)
hiddenInput.value = uploadedFileData(file, response, fileInput)
})
uppy.on('thumbnail:generated', (file, preview) => {
imagePreview.src = preview
})
}
const multipleFileUpload = (fileInput) => {
var formGroup = fileInput.parentNode
var uppy = fileUpload(fileInput)
uppy
.use(Uppy.Dashboard, {
target: formGroup,
inline: true,
height: 300,
replaceTargetContent: true,
})
uppy.on('upload-success', (file, response) => {
const hiddenField = document.createElement('input')
hiddenField.type = 'hidden'
hiddenField.name = 'album[photos_attributes]['+ Math.random().toString(36).substr(2, 9) + '][image]'
hiddenField.value = uploadedFileData(file, response, fileInput)
document.querySelector('form').appendChild(hiddenField)
})
}
const fileUpload = (fileInput) => {
const uppy = new Uppy.Core({
id: fileInput.id,
autoProceed: true,
restrictions: {
allowedFileTypes: fileInput.accept.split(','),
},
})
if (fileInput.dataset.uploadServer == 's3') {
uppy.use(Uppy.AwsS3, {
companionUrl: '/', // will call Shrine's presign endpoint mounted on `/s3/params`
})
} else {
uppy.use(Uppy.XHRUpload, {
endpoint: '/upload', // Shrine's upload endpoint
headers: { 'X-CSRF-Token': fileInput.dataset.uploadCsrfToken }
})
}
return uppy
}
const uploadedFileData = (file, response, fileInput) => {
if (fileInput.dataset.uploadServer == 's3') {
// construct uploaded file data in the format that Shrine expects
return JSON.stringify({
id: file.meta['key'].match(/^cache\/(.+)/)[1], // object key without prefix
storage: 'cache',
metadata: {
size: file.size,
filename: file.name,
mime_type: file.type,
}
})
} else {
return JSON.stringify(response.body)
}
}
document.querySelectorAll('input[type=file]').forEach((fileInput) => {
if (fileInput.multiple) {
multipleFileUpload(fileInput)
} else {
singleFileUpload(fileInput)
}
})