-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathupload.js
More file actions
358 lines (271 loc) · 9.23 KB
/
upload.js
File metadata and controls
358 lines (271 loc) · 9.23 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
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
// Initiate uploader
document.addEventListener("DOMContentLoaded", function(event) {
Uploader.init();
});
var Uploader = {
// Preview dimensions
previewWidth: 200,
previewHeight: 200,
init: function () {
// Read the comment on function
this.generateFormIds();
// Check that file API is supported
if (window.File && window.FileList && window.FileReader) {
this.addEventsListeners();
}
},
// Generate and assign unique id for every form
// When user uploads images, on server side you will be able to tell that multiple uploaded files belong to the same transaction
// So this is basically transaction ID and it makes sense to generate it in the beginning of every 'upload session' if you do not
// reload page completely.
generateFormIds: function () {
var formIdentFields = document.querySelectorAll('form input[type=hidden][name=formIdent]');
for (var i = 0; i < formIdentFields.length; i++) {
formIdentFields[i].value = this.getRandomStr(32);
}
},
// Shortcut
getById: function(id) {
return document.getElementById(id);
},
// Add events listeners
addEventsListeners: function() {
var dropzone = this.getById('dropzone');
var fileselect = this.getById('fileselect');
// Read comments on functions for details
dropzone.addEventListener('dragover', this.onDropzoneHover.bind(this));
dropzone.addEventListener('dragleave', this.onDropzoneLeave.bind(this));
dropzone.addEventListener('drop', this.onFileListChange.bind(this));
// We attach 'paste' event to window so you do not need to select a special element on the page before pasting
// But if you want you can attach it to any element, for example textarea where user writes his post, etc.
window.addEventListener('paste', this.onFileListChange.bind(this));
fileselect.addEventListener('change', this.onFileListChange.bind(this));
},
// Enable/disable dropzone styling (used when you drag&drop file on it)
styleDropzone: function (flag) {
var dropzone = this.getById('dropzone');
dropzone.className = flag ? 'hover' : '';
},
// When mouse with file over dropzone
onDropzoneHover: function(e) {
// Stop browsing from opening dropped file in browser by link
e.preventDefault();
this.styleDropzone(true);
},
// When mouse leaves dropzone
onDropzoneLeave: function() {
this.styleDropzone(false);
},
// List of added files changed
onFileListChange: function(e) {
if (e.type !== 'paste') {
// Stop browsing from opening dropped file in browser by link
e.preventDefault();
}
// if file successfully dropped - unstyle dropzone
if (e.type === 'drop') {
this.styleDropzone(false);
}
var files = [], pastedFile;
// Getting 'selected' files
if (e.target.files) {
files = e.target.files;
// Getting 'dropped' files
} else if (e.dataTransfer && e.dataTransfer.files) {
files = e.dataTransfer.files;
// Getting 'pasted' files
} else if (pastedFile = this.extractFileFromClipboard(e)) {
pastedFile.fromClipboard = true;
files = [pastedFile];
}
// Create previews for files in upload list
for (var i = 0; i < files.length; i++) {
this.processFile(files[i]);
}
},
// Extract file from clipboard
extractFileFromClipboard: function (event) {
if (event.clipboardData
&& event.clipboardData.items
&& event.clipboardData.items.length
) {
var file = event.clipboardData.items[0].getAsFile();
// Return item only if it is file (not 'text', for example)
if (file instanceof Blob) {
return file;
}
}
return null;
},
// Upload file
upload: function (file) {
// Create data object...
var formData = new FormData();
// ... and fill it up with file object and meta information
formData.append('uplFile', file);
formData.append('uplFileName', file.name);
formData.append('formIdent', document.querySelector('[name=formIdent]').value);
var xhr = new XMLHttpRequest();
xhr.upload.ident = file.ident;
xhr.upload.addEventListener('progress', this.onUploadProgress.bind(this));
xhr.onreadystatechange = this.onReadyStateChange.bind(this);
xhr.open("POST", this.getById('upload').action);
xhr.send(formData);
},
// Track progress with "progress" event
onUploadProgress: function (e) {
var xhru = e.currentTarget;
var ident = xhru.ident;
var percent = Math.round(e.loaded * 100 / e.total);
// Calculate upload % and resize progress bar
this.getPreviewBox(ident).querySelector('.progressBar').style.width = (percent + '%');
},
// Called when xhr state changes
onReadyStateChange: function (e) {
var xhr = e.currentTarget;
var ident = xhr.upload.ident;
// Upload complete
if (xhr.readyState == XMLHttpRequest.DONE) {
// Check response code
if (xhr.status === 200) {
this.onUploadSuccessful(e, ident);
} else {
this.onUploadFailed(e, ident);
}
}
},
// Called when upload of file is successful
onUploadSuccessful: function (e, ident) {
this.markImageAsUploaded(ident);
},
// Called if upload of file has failed
onUploadFailed: function (e, ident) {
this.markImageAsFailed(ident);
},
// Mark image as uploaded successfully
markImageAsUploaded: function (ident) {
this.getPreviewBox(ident).querySelector('.done').style.visibility = 'visible';
},
// Mark image as failed to upload
markImageAsFailed: function (ident) {
this.getPreviewBox(ident).querySelector('.fail').style.visibility = 'visible';
},
// Calculate thumbnail size by given original size and desired maximums
calcTnSize: function(width, height, maxWidth, maxHeight) {
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
return {
height: Math.round(height),
width: Math.round(width)
}
},
// Do actions on image: generate ident, load, init resize
processFile: function(file) {
if (!(file instanceof Blob)) {
alert('You can upload only files');
return;
}
// Check file type (something like image/png)
// but do not forget to check file on server side
if (file.type.indexOf('image') !== 0) {
alert('You can upload only images');
return;
}
if (file.fromClipboard) {
file.name = 'Clipboard.png';
}
// Assigning file ident so we could update preview image in box when it is ready
file.ident = 'imgIdent-' + this.getRandomStr(8);
this.previewCreate(file.ident, file.name);
var reader = new FileReader();
reader.fileIdent = file.ident;
reader.onload = this.onReaderReady.bind(this);
reader.readAsDataURL(file);
// Upload file right away
this.upload(file);
},
// When `FileReader` reads file from users disk
onReaderReady: function (e) {
var reader = e.currentTarget;
// Create new Img object
var img = document.createElement('img');
img.fileIdent = reader.fileIdent;
// Result contains loaded file as DataUrl string
img.src = e.target.result;
// When event occurs - image is ready for read from JS and transformation
img.onload = this.onImageReady.bind(this);
},
// Image resize logic
onImageReady: function (e) {
var img = e.currentTarget;
// Calculate thumbnail size
var nSize = this.calcTnSize(img.width, img.height, this.previewWidth, this.previewHeight);
// Create canvas element
var canvas = document.createElement('canvas');
// Set canvas size
canvas.width = nSize.width;
canvas.height = nSize.height;
// Put/resize image on canvas
canvas.getContext("2d").drawImage(img, 0, 0, nSize.width, nSize.height);
// Retrieve the result image as DataUrl
var dataurl = canvas.toDataURL('image/png');
// Update preview box with resized image
this.previewSetImage(img.fileIdent, dataurl);
},
// Create an HTML preview box: Initially it will have just a message in it but when the
// image is loaded, resized and ready - the preview box will be updated with actual image
previewCreate: function(ident, title) {
var previewsHolder = this.getById('previews');
previewsHolder.style.display = 'block';
var ds = previewsHolder.querySelector('.clearDiv');
if (ds) {
previewsHolder.removeChild(ds);
}
var html = '';
html += '<div class="previewBox" id="imgHolder-'+ident+'">';
html += ' <div class="progress">';
html += ' <div class="progressBar"></div>';
html += ' </div>';
html += ' <div class="title">';
html += ' ' + title;
html += ' <strong class="done">[done]</strong>';
html += ' <strong class="fail">[fail]</strong>';
html += ' </div>';
html += ' <div class="imgHolder">';
html += ' <br><br><br>';
html += ' <span class="spinner">🕛</span>';
html += ' Creating preview...';
html += ' </div>';
html += '</div>';
html += '<div class="clearDiv"></div>';
previewsHolder.innerHTML = previewsHolder.innerHTML + html;
},
// Update preview box with actual preview image
previewSetImage: function(ident, dataUrl) {
this.getPreviewBox(ident).querySelector('.imgHolder').innerHTML = '<img src="'+dataUrl+'" />';
},
getPreviewBox: function (ident) {
return this.getById('imgHolder-'+ident);
},
// Generate random string token
getRandomStr: function(length) {
if (!length) {
length = 8;
}
var rndStr = '';
var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0; i < length; i++ ) {
rndStr += chars.charAt(Math.floor(Math.random() * chars.length));
}
return rndStr;
}
};