Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

Blob.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /* Blob.js
  2. * A Blob, File, FileReader & URL implementation.
  3. * 2018-08-09
  4. *
  5. * By Eli Grey, http://eligrey.com
  6. * By Jimmy Wärting, https://github.com/jimmywarting
  7. * License: MIT
  8. * See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md
  9. */
  10. ;(function(){
  11. var global = typeof window === 'object'
  12. ? window : typeof self === 'object'
  13. ? self : this
  14. var BlobBuilder = global.BlobBuilder
  15. || global.WebKitBlobBuilder
  16. || global.MSBlobBuilder
  17. || global.MozBlobBuilder;
  18. global.URL = global.URL || global.webkitURL || function(href, a) {
  19. a = document.createElement('a')
  20. a.href = href
  21. return a
  22. }
  23. var origBlob = global.Blob
  24. var createObjectURL = URL.createObjectURL
  25. var revokeObjectURL = URL.revokeObjectURL
  26. var strTag = global.Symbol && global.Symbol.toStringTag
  27. var blobSupported = false
  28. var blobSupportsArrayBufferView = false
  29. var arrayBufferSupported = !!global.ArrayBuffer
  30. var blobBuilderSupported = BlobBuilder
  31. && BlobBuilder.prototype.append
  32. && BlobBuilder.prototype.getBlob;
  33. try {
  34. // Check if Blob constructor is supported
  35. blobSupported = new Blob(['ä']).size === 2
  36. // Check if Blob constructor supports ArrayBufferViews
  37. // Fails in Safari 6, so we need to map to ArrayBuffers there.
  38. blobSupportsArrayBufferView = new Blob([new Uint8Array([1,2])]).size === 2
  39. } catch(e) {}
  40. /**
  41. * Helper function that maps ArrayBufferViews to ArrayBuffers
  42. * Used by BlobBuilder constructor and old browsers that didn't
  43. * support it in the Blob constructor.
  44. */
  45. function mapArrayBufferViews(ary) {
  46. return ary.map(function(chunk) {
  47. if (chunk.buffer instanceof ArrayBuffer) {
  48. var buf = chunk.buffer;
  49. // if this is a subarray, make a copy so we only
  50. // include the subarray region from the underlying buffer
  51. if (chunk.byteLength !== buf.byteLength) {
  52. var copy = new Uint8Array(chunk.byteLength);
  53. copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
  54. buf = copy.buffer;
  55. }
  56. return buf;
  57. }
  58. return chunk;
  59. });
  60. }
  61. function BlobBuilderConstructor(ary, options) {
  62. options = options || {};
  63. var bb = new BlobBuilder();
  64. mapArrayBufferViews(ary).forEach(function(part) {
  65. bb.append(part);
  66. });
  67. return options.type ? bb.getBlob(options.type) : bb.getBlob();
  68. };
  69. function BlobConstructor(ary, options) {
  70. return new origBlob(mapArrayBufferViews(ary), options || {});
  71. };
  72. if (global.Blob) {
  73. BlobBuilderConstructor.prototype = Blob.prototype;
  74. BlobConstructor.prototype = Blob.prototype;
  75. }
  76. function FakeBlobBuilder() {
  77. function toUTF8Array(str) {
  78. var utf8 = [];
  79. for (var i=0; i < str.length; i++) {
  80. var charcode = str.charCodeAt(i);
  81. if (charcode < 0x80) utf8.push(charcode);
  82. else if (charcode < 0x800) {
  83. utf8.push(0xc0 | (charcode >> 6),
  84. 0x80 | (charcode & 0x3f));
  85. }
  86. else if (charcode < 0xd800 || charcode >= 0xe000) {
  87. utf8.push(0xe0 | (charcode >> 12),
  88. 0x80 | ((charcode>>6) & 0x3f),
  89. 0x80 | (charcode & 0x3f));
  90. }
  91. // surrogate pair
  92. else {
  93. i++;
  94. // UTF-16 encodes 0x10000-0x10FFFF by
  95. // subtracting 0x10000 and splitting the
  96. // 20 bits of 0x0-0xFFFFF into two halves
  97. charcode = 0x10000 + (((charcode & 0x3ff)<<10)
  98. | (str.charCodeAt(i) & 0x3ff));
  99. utf8.push(0xf0 | (charcode >>18),
  100. 0x80 | ((charcode>>12) & 0x3f),
  101. 0x80 | ((charcode>>6) & 0x3f),
  102. 0x80 | (charcode & 0x3f));
  103. }
  104. }
  105. return utf8;
  106. }
  107. function fromUtf8Array(array) {
  108. var out, i, len, c;
  109. var char2, char3;
  110. out = "";
  111. len = array.length;
  112. i = 0;
  113. while (i < len) {
  114. c = array[i++];
  115. switch (c >> 4)
  116. {
  117. case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
  118. // 0xxxxxxx
  119. out += String.fromCharCode(c);
  120. break;
  121. case 12: case 13:
  122. // 110x xxxx 10xx xxxx
  123. char2 = array[i++];
  124. out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
  125. break;
  126. case 14:
  127. // 1110 xxxx 10xx xxxx 10xx xxxx
  128. char2 = array[i++];
  129. char3 = array[i++];
  130. out += String.fromCharCode(((c & 0x0F) << 12) |
  131. ((char2 & 0x3F) << 6) |
  132. ((char3 & 0x3F) << 0));
  133. break;
  134. }
  135. }
  136. return out;
  137. }
  138. function isDataView(obj) {
  139. return obj && DataView.prototype.isPrototypeOf(obj)
  140. }
  141. function bufferClone(buf) {
  142. var view = new Array(buf.byteLength)
  143. var array = new Uint8Array(buf)
  144. var i = view.length
  145. while(i--) {
  146. view[i] = array[i]
  147. }
  148. return view
  149. }
  150. function encodeByteArray(input) {
  151. var byteToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  152. var output = [];
  153. for (var i = 0; i < input.length; i += 3) {
  154. var byte1 = input[i];
  155. var haveByte2 = i + 1 < input.length;
  156. var byte2 = haveByte2 ? input[i + 1] : 0;
  157. var haveByte3 = i + 2 < input.length;
  158. var byte3 = haveByte3 ? input[i + 2] : 0;
  159. var outByte1 = byte1 >> 2;
  160. var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
  161. var outByte3 = ((byte2 & 0x0F) << 2) | (byte3 >> 6);
  162. var outByte4 = byte3 & 0x3F;
  163. if (!haveByte3) {
  164. outByte4 = 64;
  165. if (!haveByte2) {
  166. outByte3 = 64;
  167. }
  168. }
  169. output.push(
  170. byteToCharMap[outByte1], byteToCharMap[outByte2],
  171. byteToCharMap[outByte3], byteToCharMap[outByte4])
  172. }
  173. return output.join('')
  174. }
  175. var create = Object.create || function (a) {
  176. function c() {}
  177. c.prototype = a;
  178. return new c
  179. }
  180. if (arrayBufferSupported) {
  181. var viewClasses = [
  182. '[object Int8Array]',
  183. '[object Uint8Array]',
  184. '[object Uint8ClampedArray]',
  185. '[object Int16Array]',
  186. '[object Uint16Array]',
  187. '[object Int32Array]',
  188. '[object Uint32Array]',
  189. '[object Float32Array]',
  190. '[object Float64Array]'
  191. ]
  192. var isArrayBufferView = ArrayBuffer.isView || function(obj) {
  193. return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
  194. }
  195. }
  196. /********************************************************/
  197. /* Blob constructor */
  198. /********************************************************/
  199. function Blob(chunks, opts) {
  200. chunks = chunks || []
  201. for (var i = 0, len = chunks.length; i < len; i++) {
  202. var chunk = chunks[i]
  203. if (chunk instanceof Blob) {
  204. chunks[i] = chunk._buffer
  205. } else if (typeof chunk === 'string') {
  206. chunks[i] = toUTF8Array(chunk)
  207. } else if (arrayBufferSupported && (ArrayBuffer.prototype.isPrototypeOf(chunk) || isArrayBufferView(chunk))) {
  208. chunks[i] = bufferClone(chunk)
  209. } else if (arrayBufferSupported && isDataView(chunk)) {
  210. chunks[i] = bufferClone(chunk.buffer)
  211. } else {
  212. chunks[i] = toUTF8Array(String(chunk))
  213. }
  214. }
  215. this._buffer = [].concat.apply([], chunks)
  216. this.size = this._buffer.length
  217. this.type = opts ? opts.type || '' : ''
  218. }
  219. Blob.prototype.slice = function(start, end, type) {
  220. var slice = this._buffer.slice(start || 0, end || this._buffer.length)
  221. return new Blob([slice], {type: type})
  222. }
  223. Blob.prototype.toString = function() {
  224. return '[object Blob]'
  225. }
  226. /********************************************************/
  227. /* File constructor */
  228. /********************************************************/
  229. function File(chunks, name, opts) {
  230. opts = opts || {}
  231. var a = Blob.call(this, chunks, opts) || this
  232. a.name = name
  233. a.lastModifiedDate = opts.lastModified ? new Date(opts.lastModified) : new Date
  234. a.lastModified = +a.lastModifiedDate
  235. return a
  236. }
  237. File.prototype = create(Blob.prototype);
  238. File.prototype.constructor = File;
  239. if (Object.setPrototypeOf)
  240. Object.setPrototypeOf(File, Blob);
  241. else {
  242. try {File.__proto__ = Blob} catch (e) {}
  243. }
  244. File.prototype.toString = function() {
  245. return '[object File]'
  246. }
  247. /********************************************************/
  248. /* FileReader constructor */
  249. /********************************************************/
  250. function FileReader() {
  251. if (!(this instanceof FileReader))
  252. throw new TypeError("Failed to construct 'FileReader': Please use the 'new' operator, this DOM object constructor cannot be called as a function.")
  253. var delegate = document.createDocumentFragment()
  254. this.addEventListener = delegate.addEventListener
  255. this.dispatchEvent = function(evt) {
  256. var local = this['on' + evt.type]
  257. if (typeof local === 'function') local(evt)
  258. delegate.dispatchEvent(evt)
  259. }
  260. this.removeEventListener = delegate.removeEventListener
  261. }
  262. function _read(fr, blob, kind) {
  263. if (!(blob instanceof Blob))
  264. throw new TypeError("Failed to execute '" + kind + "' on 'FileReader': parameter 1 is not of type 'Blob'.")
  265. fr.result = ''
  266. setTimeout(function(){
  267. this.readyState = FileReader.LOADING
  268. fr.dispatchEvent(new Event('load'))
  269. fr.dispatchEvent(new Event('loadend'))
  270. })
  271. }
  272. FileReader.EMPTY = 0
  273. FileReader.LOADING = 1
  274. FileReader.DONE = 2
  275. FileReader.prototype.error = null
  276. FileReader.prototype.onabort = null
  277. FileReader.prototype.onerror = null
  278. FileReader.prototype.onload = null
  279. FileReader.prototype.onloadend = null
  280. FileReader.prototype.onloadstart = null
  281. FileReader.prototype.onprogress = null
  282. FileReader.prototype.readAsDataURL = function(blob) {
  283. _read(this, blob, 'readAsDataURL')
  284. this.result = 'data:' + blob.type + ';base64,' + encodeByteArray(blob._buffer)
  285. }
  286. FileReader.prototype.readAsText = function(blob) {
  287. _read(this, blob, 'readAsText')
  288. this.result = fromUtf8Array(blob._buffer)
  289. }
  290. FileReader.prototype.readAsArrayBuffer = function(blob) {
  291. _read(this, blob, 'readAsText')
  292. this.result = blob._buffer.slice()
  293. }
  294. FileReader.prototype.abort = function() {}
  295. /********************************************************/
  296. /* URL */
  297. /********************************************************/
  298. URL.createObjectURL = function(blob) {
  299. return blob instanceof Blob
  300. ? 'data:' + blob.type + ';base64,' + encodeByteArray(blob._buffer)
  301. : createObjectURL.call(URL, blob)
  302. }
  303. URL.revokeObjectURL = function(url) {
  304. revokeObjectURL && revokeObjectURL.call(URL, url)
  305. }
  306. /********************************************************/
  307. /* XHR */
  308. /********************************************************/
  309. var _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send
  310. if (_send) {
  311. XMLHttpRequest.prototype.send = function(data) {
  312. if (data instanceof Blob) {
  313. this.setRequestHeader('Content-Type', data.type)
  314. _send.call(this, fromUtf8Array(data._buffer))
  315. } else {
  316. _send.call(this, data)
  317. }
  318. }
  319. }
  320. global.FileReader = FileReader
  321. global.File = File
  322. global.Blob = Blob
  323. }
  324. if (strTag) {
  325. File.prototype[strTag] = 'File'
  326. Blob.prototype[strTag] = 'Blob'
  327. FileReader.prototype[strTag] = 'FileReader'
  328. }
  329. function fixFileAndXHR() {
  330. var isIE = !!global.ActiveXObject || (
  331. '-ms-scroll-limit' in document.documentElement.style &&
  332. '-ms-ime-align' in document.documentElement.style
  333. )
  334. // Monkey patched
  335. // IE don't set Content-Type header on XHR whose body is a typed Blob
  336. // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6047383
  337. var _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send
  338. if (isIE && _send) {
  339. XMLHttpRequest.prototype.send = function(data) {
  340. if (data instanceof Blob) {
  341. this.setRequestHeader('Content-Type', data.type)
  342. _send.call(this, data)
  343. } else {
  344. _send.call(this, data)
  345. }
  346. }
  347. }
  348. try {
  349. new File([], '')
  350. } catch(e) {
  351. try {
  352. var klass = new Function('class File extends Blob {' +
  353. 'constructor(chunks, name, opts) {' +
  354. 'opts = opts || {};' +
  355. 'super(chunks, opts || {});' +
  356. 'this.name = name;' +
  357. 'this.lastModifiedDate = opts.lastModified ? new Date(opts.lastModified) : new Date;' +
  358. 'this.lastModified = +this.lastModifiedDate;' +
  359. '}};' +
  360. 'return new File([], ""), File'
  361. )()
  362. global.File = klass
  363. } catch(e) {
  364. var klass = function(b, d, c) {
  365. var blob = new Blob(b, c)
  366. var t = c && void 0 !== c.lastModified ? new Date(c.lastModified) : new Date
  367. blob.name = d
  368. blob.lastModifiedDate = t
  369. blob.lastModified = +t
  370. blob.toString = function() {
  371. return '[object File]'
  372. }
  373. if (strTag)
  374. blob[strTag] = 'File'
  375. return blob
  376. }
  377. global.File = klass
  378. }
  379. }
  380. }
  381. if (blobSupported) {
  382. fixFileAndXHR()
  383. global.Blob = blobSupportsArrayBufferView ? global.Blob : BlobConstructor
  384. } else if (blobBuilderSupported) {
  385. fixFileAndXHR()
  386. global.Blob = BlobBuilderConstructor;
  387. } else {
  388. FakeBlobBuilder()
  389. }
  390. })();