Conversions.js
1.84 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
/**
* Conversions.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* Converts blob/uris back and forth.
*
* @private
* @class tinymce.file.Conversions
*/
define("tinymce/file/Conversions", [
"tinymce/util/Promise"
], function(Promise) {
function blobUriToBlob(url) {
return new Promise(function(resolve) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (this.status == 200) {
resolve(this.response);
}
};
xhr.send();
});
}
function parseDataUri(uri) {
var type, matches;
uri = decodeURIComponent(uri).split(',');
matches = /data:([^;]+)/.exec(uri[0]);
if (matches) {
type = matches[1];
}
return {
type: type,
data: uri[1]
};
}
function dataUriToBlob(uri) {
return new Promise(function(resolve) {
var str, arr, i;
uri = parseDataUri(uri);
// Might throw error if data isn't proper base64
try {
str = atob(uri.data);
} catch (e) {
resolve(new Blob([]));
return;
}
arr = new Uint8Array(str.length);
for (i = 0; i < arr.length; i++) {
arr[i] = str.charCodeAt(i);
}
resolve(new Blob([arr], {type: uri.type}));
});
}
function uriToBlob(url) {
if (url.indexOf('blob:') === 0) {
return blobUriToBlob(url);
}
if (url.indexOf('data:') === 0) {
return dataUriToBlob(url);
}
return null;
}
function blobToDataUri(blob) {
return new Promise(function(resolve) {
var reader = new FileReader();
reader.onloadend = function() {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});
}
return {
uriToBlob: uriToBlob,
blobToDataUri: blobToDataUri,
parseDataUri: parseDataUri
};
});