-
-
Notifications
You must be signed in to change notification settings - Fork 625
Expand file tree
/
Copy pathUploader.vue
More file actions
315 lines (264 loc) · 9.33 KB
/
Uploader.vue
File metadata and controls
315 lines (264 loc) · 9.33 KB
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
<script>
import { Upload } from 'upload';
import { nanoid as uniqid } from 'nanoid';
import { h } from 'vue';
export default {
emits: ['updated', 'upload-complete', 'error'],
render() {
const fileField = h('input', {
class: { hidden: true },
type: 'file',
multiple: true,
ref: 'nativeFileField',
});
const events = this.enabled
? {
onDragenter: this.dragenter,
onDragover: this.dragover,
onDragleave: this.dragleave,
onDrop: this.drop,
}
: {};
return h(
'div',
{
class: 'h-full',
...events,
},
[
h('div', { class: ['h-full', { 'pointer-events-none': this.dragging }] }, [
fileField,
...this.$slots.default({ dragging: this.enabled ? this.dragging : false }),
]),
],
);
},
props: {
enabled: {
type: Boolean,
default: () => true,
},
container: String,
path: String,
url: { type: String, default: () => cp_url('assets') },
extraData: {
type: Object,
default: () => ({}),
},
},
data() {
return {
dragging: false,
uploads: [],
};
},
mounted() {
this.$refs.nativeFileField.addEventListener('change', this.addNativeFileFieldSelections);
},
beforeUnmount() {
this.$refs.nativeFileField.removeEventListener('change', this.addNativeFileFieldSelections);
},
watch: {
uploads: {
deep: true,
handler(uploads) {
this.$emit('updated', uploads);
this.processUploadQueue();
},
},
},
computed: {
activeUploads() {
return this.uploads.filter((u) => u.instance.state === 'started');
},
},
methods: {
browse() {
this.$refs.nativeFileField.click();
},
addNativeFileFieldSelections(e) {
for (let i = 0; i < e.target.files.length; i++) {
this.addFile(e.target.files[i]);
}
},
dragenter(e) {
e.stopPropagation();
e.preventDefault();
this.dragging = true;
},
dragover(e) {
e.stopPropagation();
e.preventDefault();
},
dragleave(e) {
// When dragging over a child, the parent will trigger a dragleave.
if (e.target !== e.currentTarget) return;
this.dragging = false;
},
drop(e) {
e.stopPropagation();
e.preventDefault();
this.dragging = false;
const { files, items } = e.dataTransfer;
// Handle DataTransferItems if browser supports dropping of folders
if (items && items.length && items[0].webkitGetAsEntry) {
this.addFilesFromDataTransferItems(items);
} else {
this.addFilesFromFileList(files);
}
},
addFilesFromFileList(files) {
for (let i = 0; i < files.length; i++) {
this.addFile(files[i]);
}
},
addFilesFromDataTransferItems(items) {
for (let i = 0; i < items.length; i++) {
let item = items[i];
if (item.webkitGetAsEntry) {
const entry = item.webkitGetAsEntry();
if (entry?.isFile) {
this.addFile(item.getAsFile());
} else if (entry?.isDirectory) {
this.addFilesFromDirectory(entry, entry.name);
}
} else if (item.getAsFile) {
if (item.kind === 'file' || !item.kind) {
this.addFile(item.getAsFile());
}
}
}
},
addFilesFromDirectory(directory, path) {
const reader = directory.createReader();
const readEntries = () =>
reader.readEntries((entries) => {
if (!entries.length) return;
for (let entry of entries) {
if (entry.isFile) {
entry.file((file) => {
if (!file.name.startsWith('.')) {
file.relativePath = path;
this.addFile(file);
}
});
} else if (entry.isDirectory) {
this.addFilesFromDirectory(entry, `${path}/${entry.name}`);
}
}
// Handle directories with more than 100 files in Chrome
readEntries();
}, console.error);
return readEntries();
},
addFile(file, data = {}) {
if (!this.enabled) return;
const id = uniqid();
const upload = this.makeUpload(id, file, data);
this.uploads.push({
id,
basename: file.name,
extension: file.name.split('.').pop(),
percent: 0,
errorMessage: null,
errorStatus: null,
instance: upload,
retry: (opts) => this.retry(id, opts),
});
},
findUpload(id) {
return this.uploads.find((u) => u.id === id);
},
findUploadIndex(id) {
return this.uploads.findIndex((u) => u.id === id);
},
makeUpload(id, file, data = {}) {
const upload = new Upload({
url: this.url,
form: this.makeFormData(file, data),
headers: {
Accept: 'application/json',
},
});
upload.on('progress', (progress) => {
this.findUpload(id).percent = progress * 100;
});
return upload;
},
makeFormData(file, data = {}) {
const form = new FormData();
form.append('file', file);
// Pass along the relative path of files uploaded as a directory
if (file.relativePath) {
form.append('relativePath', file.relativePath);
}
let parameters = {
...this.extraData,
container: this.container,
folder: this.path,
_token: Statamic.$config.get('csrfToken'),
};
for (let key in parameters) {
form.append(key, parameters[key]);
}
for (let key in data) {
form.append(key, data[key]);
}
return form;
},
processUploadQueue() {
// If we're already uploading, don't start another
if (this.activeUploads.length) return;
// Make sure we're not grabbing a running or failed upload
const upload = this.uploads.find((u) => u.instance.state === 'new' && !u.errorMessage);
if (!upload) return;
const id = upload.id;
upload.instance.upload().then((response) => {
let json = null;
try {
json = JSON.parse(response.data);
} catch (error) {
// If it fails, it's probably because the response is HTML.
}
response.status === 200
? this.handleUploadSuccess(id, json)
: this.handleUploadError(id, response.status, json);
this.processUploadQueue();
});
},
handleUploadSuccess(id, response) {
this.$emit('upload-complete', response.data, this.uploads);
this.uploads.splice(this.findUploadIndex(id), 1);
this.handleToasts(response._toasts ?? []);
},
handleUploadError(id, status, response) {
const upload = this.findUpload(id);
let msg = response?.message;
if (!msg) {
if (status === 413) {
msg = __('Upload failed. The file is larger than is allowed by your server.');
} else {
msg = __('Upload failed. The file might be larger than is allowed by your server.');
}
} else {
if ([422, 409].includes(status)) {
msg = Object.values(response.errors)[0][0]; // Get first validation message.
}
}
this.handleToasts(response?._toasts ?? []);
upload.errorMessage = msg;
upload.errorStatus = status;
this.$emit('error', upload, this.uploads);
this.processUploadQueue();
},
handleToasts(toasts) {
toasts.forEach((toast) => Statamic.$toast[toast.type](toast.message, { duration: toast.duration }));
},
retry(id, args) {
let file = this.findUpload(id).instance.form.get('file');
this.addFile(file, args);
this.uploads.splice(this.findUploadIndex(id), 1);
},
},
};
</script>