forked from MrSwitch/hello.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathskydrive_upload.html
630 lines (527 loc) · 15.3 KB
/
skydrive_upload.html
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
<!DOCTYPE html>
<link rel="stylesheet" href="/adorn/adorn.css"/>
<script src="/adorn/adorn.js" async></script>
<script src="client_ids.js"></script>
<title>Simple SkyDrive Demo</title>
<style>
img{
position: fixed;
top:0;
left:50%;
width:200px;
border:1px solid #ccc;
padding:10px;
}
img:nth-child(2n){
-webkit-transform:rotate(10deg);
-moz-transform:rotate(10deg);
-ms-transform:rotate(10deg);
transform:rotate(10deg);
}
img:nth-child(3n){
-webkit-transform:rotate(-10deg);
-moz-transform:rotate(-10deg);
-ms-transform:rotate(-10deg);
transform:rotate(-10deg);
}
</style>
<h1>Simple Skydrive demo</h1>
<blockquote>
<p>This demo uses OAuth2 and CORS (or JSONP) to make some REST calls which navigate the Windows Live Graph API to get some photos out of Skydrive. It is PLUGIN-FREE!</p>
<p>If running locally, <a href="http://manage.dev.live.com/">register your development domain</a> and replace WINDOWS_CLIENT_ID (below) with the client_id you are assigned</p>
</blockquote>
<p>Start by logging in <button onclick="login()">Login</button></p>
<blockquote>
<b>1. Create an Album</b>
<form>
<label>Album name </label>
<input type="text" id="new_name" name="name" value="New Album Name"/>
<br />
<label>Album description </label>
<textarea id="new_description" name="description">This is a test album</textarea>
<button type="button" onclick="createAlbum(this.form)">Upload</button>
</form>
<b>2. Select a file</b>
<form>
<input type="file" name="file" id="file"/>
</form>
</br>
<b>pick an album as the destination</b>
<select id="select"></select>
</br>
<button onclick="postPhoto( select.value, document.getElementById('file').form )">Upload</button>
<button onclick="xhrUpload( select.value, document.getElementById('file').files[0] )">Upload XHR</button>
<div id="result"></div>
</blockquote>
<script>
function login(){
window.location = 'https://oauth.live.com/authorize'+
'?client_id='+WINDOWS_CLIENT_ID+
'&scope=wl.skydrive_update'+
'&response_type=token'+
'&redirect_uri='+encodeURIComponent(window.location.href);
}
var access_token = (window.location.hash||window.location.search).match(/access_token=([^&]+)/);
if(access_token){
// Save the first match
localStorage.setItem("access_token", decodeURIComponent(access_token[1]));
}
var json_counter=0;
function jsonp(path,callback){
// Make the anonymous function. not anonymous
var callback_name = 'jsonp_' + json_counter++;
window[callback_name] = callback;
// Add the callback name to the path
path = path.replace(/\=\?/, '='+callback_name);
// find a place to insert the script tag
var sibling = document.getElementsByTagName('script')[0];
// Create the script tag
var script = document.createElement('script');
script.src = path;
sibling.parentNode.insertBefore(script,sibling);
}
//
// Param
// Explode/Encode the parameters of an URL string/object
// @param string s, String to decode
//
function _param(s){
var b,
a = {},
m;
if(typeof(s)==='string'){
m = s.replace(/^[\#\?]/,'').match(/([^=\/\&]+)=([^\&]+)/g);
if(m){
for(var i=0;i<m.length;i++){
b = m[i].split('=');
a[b[0]] = decodeURIComponent( b[1] );
}
}
return a;
}
else {
var o = s;
a = [];
for( var x in o ){if(o.hasOwnProperty(x)){
if( o.hasOwnProperty(x) ){
a.push( [x, o[x] === '?' ? '?' : encodeURIComponent(o[x]) ].join('=') );
}
}}
return a.join('&');
}
}
</script>
<p>This is the crux of what this demo is showing. postPhoto uploads the file selected in the file input element to the path of the album. It then creates an anchor tag to the uploaded file.</p>
<script>
function createAlbum(form){
var token = localStorage.getItem("access_token");
if(token){
httpRequest( "POST", 'https://apis.live.net/v5.0/me/albums?access_token='+token,
{
name: form.elements['name'].value,
description: form.elements['description'].value
},
function(r){
if(!r||r.error){
alert(r.error.message);
return;
}
var opt = document.createElement('option');
opt.value=this.upload_location;
opt.innerHTML = this.name;
document.getElementById('select').appendChild(opt);
});
}
else{
alert("Please click the login button first");
}
}
</script>
<script class="pre">
function postPhoto(path, fileInputElement){
var token = localStorage.getItem("access_token");
if(token){
// Post a photo up
httpRequest( "POST", path + '?access_token=' + token, {
file : fileInputElement
}, function(r){
console.log(r);
var a = document.createElement('a');
a.href = r.source;
a.innerHTML = r.name;
a.target = "_blank";
document.getElementById('result').appendChild(a);
}, function(e){
console.log("PROGRESS");
console.log(e);
});
}
else{
alert("Please click the login button first");
}
}
</script>
<script>
function xhrUpload(path, file){
var token = localStorage.getItem("access_token");
// Initiate XML Instance
var xhr = new XMLHttpRequest();
xhr.onload = xhr.onerror = function(e){
var text = xhr.responseText;
console.log(text?JSON.parse(text):{error:{message:"Post Failed"}});
};
xhr.open("POST", path + '?access_token=' + token, true);
var fd = new FormData();
fd.append('file', file);
xhr.send( fd );
}
</script>
<script class="pre">
function xhrRequest(method, url, data, complete, progress){
var xhr = new XMLHttpRequest();
// xhr.responseType = "json"; // is not widely supported as yet
xhr.onload = function(e){
var text = xhr.responseText;
complete(text?JSON.parse(text):{error:{message:"Could not get resource"}});
};
xhr.onerror = function(e){
var text = xhr.responseText;
complete(text?JSON.parse(text):{error:{message:"Post failed"}})
};
xhr.onprogress = progress;
xhr.open(method, url, true);
if(data){
// Windows unique, convert to a JSON string if this contains binary data
if(!has_binary(data)){
data = JSON.stringify(data);
xhr.setRequestHeader("Content-Type", 'application/json');
}
// Create FormData
else if(!(data instanceof FormData)){
// Loop through and add formData
var f = new FormData();
for( var x in data )if(data.hasOwnProperty(x)){
f.append(x, data[x]);
}
data = f;
}
}
xhr.send( data || null );
}
</script>
<script class="pre">
function httpRequest(method, url, data, complete, progress){
var p = {
data : data
}
if( p.data && !_dataToJSON(p) ){
iframeHack(url, p.data, callback);
return;
}
data = p.data;
// IE10, FF, Chrome
if('withCredentials' in new XMLHttpRequest()){
xhrRequest( method, url, data, complete, progress );
}
else{
// windows convert POST to GET
// This perhaps isn't that great
var qs;
if( data ){
data.method = 'post';
qs = data;
data=null;
}
// Else add the callback on to the URL
if(!data){
jsonp(url+(qs?'&'+_param(qs):'')+"&callback=?", complete);
}
else{
iframeHack(url, data, complete);
}
}
}
//
// Some of the providers require that only MultiPart is used with non-binary forms.
// This function checks whether the form contains binary data
function has_binary(data){
if(("FormData" in window && data instanceof FormData)||
("File" in window && data instanceof File)||
("Blob" in window && data instanceof Blob)
){
return true;
}
for(var x in data ) if(data.hasOwnProperty(x)){
if( data[x] instanceof HTMLElement && data[x].type === 'file' ){
return true;
}
}
return false;
}
</script>
<p>IFrameHack</p>
<script class="pre">
// user out little helped function to read the parameters
var qs = _param(window.location.hash);
// If there exists a state and a result in the hashtag then we need to call these on the parent.
// Result is serialized JSON string.
if(qs&&qs.state&&qs.result){
// trigger a function in the parent
window.parent[qs.state](JSON.parse(qs.result));
}
</script>
<p>This Form+iFrame+hash hack lets us attach a number of different data types to be posted.</p>
<ul>
<li>InputElement: Post a single input element within a form
<li>InputForm: Post an entire form and all its values
<li>JSON: Turn a JSON key=>value or a key=>InputElement hash into a form post
</ul>
<script class="pre">
function iframeHack(url, data, callback){
// This hack needs a form
var form = null,
reenableAfterSubmit = [],
newform;
// What is the name of the callback to contain
// We'll also use this to name the iFrame
var state = "ifrmhack_"+parseInt(Math.random()*1e6).toString(16);
// Save the callback to the window
window[state] = function(r){
try{
// remove the iframe from the page.
win.parentNode.removeChild(win);
// remove the form
if(newform){
newform.parentNode.removeChild(newform);
}
}
catch(e){console.error("could not remove iframe")}
// reenable the disabled form
for(var i=0;i<reenableAfterSubmit.length;i++){
if(reenableAfterSubmit[i]){
reenableAfterSubmit[i].setAttribute('disabled', false);
}
}
// fire the callback
callback(r);
}
// Build the iframe window
var win = document.createElement('iframe');
win.id = state;
win.name = state;
win.height = "1px";
win.width = "1px";
document.body.appendChild(win);
// Add some additional query parameters to the URL
url += "&suppress_response_codes=true&redirect_uri="+encodeURIComponent(window.location.href.replace(/#.*$/,'')) +"&state="+state;
// if we are just posting a single item
if(data instanceof HTMLInputElement){
// get the parent form
var form = data.form;
// Loop through and disable all of its siblings
for( var i = 0; i < form.elements.length; i++ ){
if(form.elements[i] !== data){
form.elements[i].setAttribute('disabled',true);
}
}
// Move the focus to the form
data = form;
}
// Posting a form
if(data instanceof HTMLFormElement){
// This is a form element
var form = data;
// Does this form need to be a multipart form?
for( var i = 0; i < form.elements.length; i++ ){
if(!form.elements[i].disabled && form.elements[i].type === 'file'){
form.setAttribute('enctype', 'multipart/form-data');
form.elements[i].setAttribute('name', 'file');
}
}
}
else{
// Its not a form element,
// Therefore it must be a JSON object of Key=>Value or Key=>Element
// If anyone of those values are a input type=file we shall shall insert its siblings into the form for which it belongs.
for(var x in data) if(data.hasOwnProperty(x)){
// is this an input Element?
if( data[x] instanceof HTMLInputElement && data[x].type === 'file' ){
form = data[x].form;
form.setAttribute('enctype', 'multipart/form-data');
}
}
// Do If there is no defined form element, lets create one.
if(!form){
// Build form
form = document.createElement('form');
form.height = "1px";
form.width = "1px";
document.body.appendChild(form);
newform = form;
}
// Add elements to the form if they dont exist
for(var x in data) if(data.hasOwnProperty(x)){
// Is this an element?
var el = ( data[x] instanceof HTMLInputElement || data[x] instanceof HTMLTextAreaElement || data[x] instanceof HTMLSelectElement );
// is this not an input element, or one that exists outside the form.
if( !el || data[x].form !== form ){
// Does an element have the same name?
if(form.elements[x]){
// Remove it.
form.elements[x].parentNode.removeChild(form.elements[x]);
}
// Create an input element
var input = document.createElement('input');
input.setAttribute('name', x);
input.value = data[x];
// Does it have a value attribute?
if(el){
input.value = data[x].value;
}
else if(el instanceof HTMLElement){
input.value = data[x].innerHTML || data[x].innerText;
}
form.appendChild(input);
}
// it is an element, which exists within the form, but the name is wrong
else if( el && data[x].name !== x){
data[x].setAttribute('name', x);
data[x].name = x;
}
}
// Disable elements from within the form if they weren't specified
for(var i=0;i<form.children.length;i++){
// Does the same name and value exist in the parent
if( !( form.children[i].name in data ) && form.children[i].getAttribute('disabled') !== true ) {
// disable
form.children[i].setAttribute('disabled',true);
// add re-enable to callback
reenableAfterSubmit.push(form.children[i]);
}
}
}
// Set the target of the form
form.setAttribute('method', 'post');
form.setAttribute('action', url);
form.setAttribute('target', state);
// Submit the form
setTimeout(function(){
form.submit();
},30);
}
</script>
<script>
//
//
//
function _dataToJSON(p){
var data = p.data;
// Is data a form object
if( data instanceof HTMLFormElement ){
// Get the first FormElement Item if its an type=file
var kids = data.children;
var json = {};
// Create a data string
for(var i=0;i<kids.length;i++){
// Is this a file, does the browser not support 'files' and 'FormData'?
if( kids[i].type === 'file' ){
// the browser does not XHR2
if("FormData" in window){
json = new FormData(data);
break;
}
else if( !("files" in kids[i]) ){
return false;
}
}
else{
json[ kids[i].name ] = kids[i].value || kids[i].innerHTML;
}
}
// Convert to a postable querystring
data = json;
}
// Is this a form input element?
if( data instanceof HTMLInputElement ){
// Get the Input Element
// Do we have a Blob data?
if("files" in data){
var o = {};
o[ data.name ] = data.files;
// Turn it into a FileList
data = o;
}
else{
// This is old school, we have to perform the FORM + IFRAME + HASHTAG hack
return false;
}
}
// Is data a blob, File, FileList?
if( ("File" in window && data instanceof File)
|| ("Blob" in window && data instanceof Blob)
|| ("FileList" in window && data instanceof FileList) ){
// Convert to a JSON object
data = {'file' : data};
}
// Loop through data if its not FormData it must now be a JSON object
if( !( "FormData" in window && data instanceof FormData ) ){
// Loop through the object
for(var x in data) if(data.hasOwnProperty(x)){
// FileList Object?
if("FileList" in window && data[x] instanceof FileList){
// Get first record only
if(data[x].length===1){
data[x] = data[x][0];
}
else{
console.error("We were expecting the FileList to contain one file");
}
}
else if( data[x] instanceof HTMLInputElement && data[x].type === 'file' ){
if( ("files" in data[x] ) ){
data[x] = data[x].files[0];
}
else{
// this does not support HTML5 forms FileList
return false;
}
}
else if( data[x] instanceof HTMLInputElement
&& data[x] instanceof HTMLSelectElement
&& data[x] instanceof HTMLTextAreaElement
){
data[x] = data[x].value;
}
else if( data[x] instanceof Element ){
data[x] = data[x].innerHTML || data[x].innerText;
}
}
}
p.data = data;
return true;
}
</script>
<script>
if(localStorage.getItem("access_token")){
// Token
var token = localStorage.getItem("access_token");
// Make httpRequest
// Retrieve all albums in SkyDrive
httpRequest("GET", 'https://apis.live.net/v5.0/me/albums?access_token='+token, null, function(r){
// Valid
if(!r||r.error){
alert("You have an error: "+r.error.message);
localStorage.removeItem("access_token");
return;
}
// Loop through the results
for(var i=0;i<r.data.length;i++){
var obj = r.data[i];
var opt = document.createElement('option');
opt.value = obj.upload_location;
opt.innerHTML = obj.name;
document.getElementById('select').appendChild(opt);
}
});
}
</script>