ParseFile.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /**
  2. * Copyright (c) 2015-present, Parse, LLC.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. * @flow
  10. */
  11. /* global XMLHttpRequest, Blob */
  12. import CoreManager from './CoreManager';
  13. /*:: import type { FullOptions } from './RESTController';*/
  14. let XHR = null;
  15. if (typeof XMLHttpRequest !== 'undefined') {
  16. XHR = XMLHttpRequest;
  17. }
  18. /*:: type Base64 = { base64: string };*/
  19. /*:: type Uri = { uri: string };*/
  20. /*:: type FileData = Array<number> | Base64 | Blob | Uri;*/
  21. /*:: export type FileSource = {
  22. format: 'file';
  23. file: Blob;
  24. type: string
  25. } | {
  26. format: 'base64';
  27. base64: string;
  28. type: string
  29. } | {
  30. format: 'uri';
  31. uri: string;
  32. type: string
  33. };*/
  34. const dataUriRegexp = /^data:([a-zA-Z]+\/[-a-zA-Z0-9+.]+)(;charset=[a-zA-Z0-9\-\/]*)?;base64,/;
  35. function b64Digit(number
  36. /*: number*/
  37. )
  38. /*: string*/
  39. {
  40. if (number < 26) {
  41. return String.fromCharCode(65 + number);
  42. }
  43. if (number < 52) {
  44. return String.fromCharCode(97 + (number - 26));
  45. }
  46. if (number < 62) {
  47. return String.fromCharCode(48 + (number - 52));
  48. }
  49. if (number === 62) {
  50. return '+';
  51. }
  52. if (number === 63) {
  53. return '/';
  54. }
  55. throw new TypeError('Tried to encode large digit ' + number + ' in base64.');
  56. }
  57. /**
  58. * A Parse.File is a local representation of a file that is saved to the Parse
  59. * cloud.
  60. * @alias Parse.File
  61. */
  62. class ParseFile {
  63. /*:: _name: string;*/
  64. /*:: _url: ?string;*/
  65. /*:: _source: FileSource;*/
  66. /*:: _previousSave: ?Promise<ParseFile>;*/
  67. /*:: _data: ?string;*/
  68. /**
  69. * @param name {String} The file's name. This will be prefixed by a unique
  70. * value once the file has finished saving. The file name must begin with
  71. * an alphanumeric character, and consist of alphanumeric characters,
  72. * periods, spaces, underscores, or dashes.
  73. * @param data {Array} The data for the file, as either:
  74. * 1. an Array of byte value Numbers, or
  75. * 2. an Object like { base64: "..." } with a base64-encoded String.
  76. * 3. an Object like { uri: "..." } with a uri String.
  77. * 4. a File object selected with a file upload control. (3) only works
  78. * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
  79. * For example:
  80. * <pre>
  81. * var fileUploadControl = $("#profilePhotoFileUpload")[0];
  82. * if (fileUploadControl.files.length > 0) {
  83. * var file = fileUploadControl.files[0];
  84. * var name = "photo.jpg";
  85. * var parseFile = new Parse.File(name, file);
  86. * parseFile.save().then(function() {
  87. * // The file has been saved to Parse.
  88. * }, function(error) {
  89. * // The file either could not be read, or could not be saved to Parse.
  90. * });
  91. * }</pre>
  92. * @param type {String} Optional Content-Type header to use for the file. If
  93. * this is omitted, the content type will be inferred from the name's
  94. * extension.
  95. */
  96. constructor(name
  97. /*: string*/
  98. , data
  99. /*:: ?: FileData*/
  100. , type
  101. /*:: ?: string*/
  102. ) {
  103. const specifiedType = type || '';
  104. this._name = name;
  105. if (data !== undefined) {
  106. if (Array.isArray(data)) {
  107. this._data = ParseFile.encodeBase64(data);
  108. this._source = {
  109. format: 'base64',
  110. base64: this._data,
  111. type: specifiedType
  112. };
  113. } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
  114. this._source = {
  115. format: 'file',
  116. file: data,
  117. type: specifiedType
  118. };
  119. } else if (data && typeof data.uri === 'string' && data.uri !== undefined) {
  120. this._source = {
  121. format: 'uri',
  122. uri: data.uri,
  123. type: specifiedType
  124. };
  125. } else if (data && typeof data.base64 === 'string') {
  126. const base64 = data.base64;
  127. const commaIndex = base64.indexOf(',');
  128. if (commaIndex !== -1) {
  129. const matches = dataUriRegexp.exec(base64.slice(0, commaIndex + 1)); // if data URI with type and charset, there will be 4 matches.
  130. this._data = base64.slice(commaIndex + 1);
  131. this._source = {
  132. format: 'base64',
  133. base64: this._data,
  134. type: matches[1]
  135. };
  136. } else {
  137. this._data = base64;
  138. this._source = {
  139. format: 'base64',
  140. base64: base64,
  141. type: specifiedType
  142. };
  143. }
  144. } else {
  145. throw new TypeError('Cannot create a Parse.File with that data.');
  146. }
  147. }
  148. }
  149. /**
  150. * Return the data for the file, downloading it if not already present.
  151. * Data is present if initialized with Byte Array, Base64 or Saved with Uri.
  152. * Data is cleared if saved with File object selected with a file upload control
  153. *
  154. * @return {Promise} Promise that is resolve with base64 data
  155. */
  156. async getData()
  157. /*: Promise<String>*/
  158. {
  159. if (this._data) {
  160. return this._data;
  161. }
  162. if (!this._url) {
  163. throw new Error('Cannot retrieve data for unsaved ParseFile.');
  164. }
  165. const controller = CoreManager.getFileController();
  166. const result = await controller.download(this._url);
  167. this._data = result.base64;
  168. return this._data;
  169. }
  170. /**
  171. * Gets the name of the file. Before save is called, this is the filename
  172. * given by the user. After save is called, that name gets prefixed with a
  173. * unique identifier.
  174. * @return {String}
  175. */
  176. name()
  177. /*: string*/
  178. {
  179. return this._name;
  180. }
  181. /**
  182. * Gets the url of the file. It is only available after you save the file or
  183. * after you get the file from a Parse.Object.
  184. * @param {Object} options An object to specify url options
  185. * @return {String}
  186. */
  187. url(options
  188. /*:: ?: { forceSecure?: boolean }*/
  189. )
  190. /*: ?string*/
  191. {
  192. options = options || {};
  193. if (!this._url) {
  194. return;
  195. }
  196. if (options.forceSecure) {
  197. return this._url.replace(/^http:\/\//i, 'https://');
  198. } else {
  199. return this._url;
  200. }
  201. }
  202. /**
  203. * Saves the file to the Parse cloud.
  204. * @param {Object} options
  205. * * Valid options are:<ul>
  206. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  207. * be used for this request.
  208. * <li>progress: In Browser only, callback for upload progress
  209. * </ul>
  210. * @return {Promise} Promise that is resolved when the save finishes.
  211. */
  212. save(options
  213. /*:: ?: FullOptions*/
  214. ) {
  215. options = options || {};
  216. const controller = CoreManager.getFileController();
  217. if (!this._previousSave) {
  218. if (this._source.format === 'file') {
  219. this._previousSave = controller.saveFile(this._name, this._source, options).then(res => {
  220. this._name = res.name;
  221. this._url = res.url;
  222. this._data = null;
  223. return this;
  224. });
  225. } else if (this._source.format === 'uri') {
  226. this._previousSave = controller.download(this._source.uri).then(result => {
  227. const newSource = {
  228. format: 'base64',
  229. base64: result.base64,
  230. type: result.contentType
  231. };
  232. this._data = result.base64;
  233. return controller.saveBase64(this._name, newSource, options);
  234. }).then(res => {
  235. this._name = res.name;
  236. this._url = res.url;
  237. return this;
  238. });
  239. } else {
  240. this._previousSave = controller.saveBase64(this._name, this._source, options).then(res => {
  241. this._name = res.name;
  242. this._url = res.url;
  243. return this;
  244. });
  245. }
  246. }
  247. if (this._previousSave) {
  248. return this._previousSave;
  249. }
  250. }
  251. toJSON()
  252. /*: { name: ?string, url: ?string }*/
  253. {
  254. return {
  255. __type: 'File',
  256. name: this._name,
  257. url: this._url
  258. };
  259. }
  260. equals(other
  261. /*: mixed*/
  262. )
  263. /*: boolean*/
  264. {
  265. if (this === other) {
  266. return true;
  267. } // Unsaved Files are never equal, since they will be saved to different URLs
  268. return other instanceof ParseFile && this.name() === other.name() && this.url() === other.url() && typeof this.url() !== 'undefined';
  269. }
  270. static fromJSON(obj)
  271. /*: ParseFile*/
  272. {
  273. if (obj.__type !== 'File') {
  274. throw new TypeError('JSON object does not represent a ParseFile');
  275. }
  276. const file = new ParseFile(obj.name);
  277. file._url = obj.url;
  278. return file;
  279. }
  280. static encodeBase64(bytes
  281. /*: Array<number>*/
  282. )
  283. /*: string*/
  284. {
  285. const chunks = [];
  286. chunks.length = Math.ceil(bytes.length / 3);
  287. for (let i = 0; i < chunks.length; i++) {
  288. const b1 = bytes[i * 3];
  289. const b2 = bytes[i * 3 + 1] || 0;
  290. const b3 = bytes[i * 3 + 2] || 0;
  291. const has2 = i * 3 + 1 < bytes.length;
  292. const has3 = i * 3 + 2 < bytes.length;
  293. chunks[i] = [b64Digit(b1 >> 2 & 0x3F), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0F), has2 ? b64Digit(b2 << 2 & 0x3C | b3 >> 6 & 0x03) : '=', has3 ? b64Digit(b3 & 0x3F) : '='].join('');
  294. }
  295. return chunks.join('');
  296. }
  297. }
  298. const DefaultController = {
  299. saveFile: function (name
  300. /*: string*/
  301. , source
  302. /*: FileSource*/
  303. , options
  304. /*:: ?: FullOptions*/
  305. ) {
  306. if (source.format !== 'file') {
  307. throw new Error('saveFile can only be used with File-type sources.');
  308. } // To directly upload a File, we use a REST-style AJAX request
  309. const headers = {
  310. 'X-Parse-Application-ID': CoreManager.get('APPLICATION_ID'),
  311. 'Content-Type': source.type || (source.file ? source.file.type : null)
  312. };
  313. const jsKey = CoreManager.get('JAVASCRIPT_KEY');
  314. if (jsKey) {
  315. headers['X-Parse-JavaScript-Key'] = jsKey;
  316. }
  317. let url = CoreManager.get('SERVER_URL');
  318. if (url[url.length - 1] !== '/') {
  319. url += '/';
  320. }
  321. url += 'files/' + name;
  322. return CoreManager.getRESTController().ajax('POST', url, source.file, headers, options).then(res => res.response);
  323. },
  324. saveBase64: function (name
  325. /*: string*/
  326. , source
  327. /*: FileSource*/
  328. , options
  329. /*:: ?: FullOptions*/
  330. ) {
  331. if (source.format !== 'base64') {
  332. throw new Error('saveBase64 can only be used with Base64-type sources.');
  333. }
  334. const data
  335. /*: { base64: any; _ContentType?: any }*/
  336. = {
  337. base64: source.base64
  338. };
  339. if (source.type) {
  340. data._ContentType = source.type;
  341. }
  342. return CoreManager.getRESTController().request('POST', 'files/' + name, data, options);
  343. },
  344. download: function (uri) {
  345. if (XHR) {
  346. return this.downloadAjax(uri);
  347. } else {
  348. return Promise.reject('Cannot make a request: No definition of XMLHttpRequest was found.');
  349. }
  350. },
  351. downloadAjax: function (uri) {
  352. return new Promise((resolve, reject) => {
  353. const xhr = new XHR();
  354. xhr.open('GET', uri, true);
  355. xhr.responseType = 'arraybuffer';
  356. xhr.onerror = function (e) {
  357. reject(e);
  358. };
  359. xhr.onreadystatechange = function () {
  360. if (xhr.readyState !== 4) {
  361. return;
  362. }
  363. const bytes = new Uint8Array(this.response);
  364. resolve({
  365. base64: ParseFile.encodeBase64(bytes),
  366. contentType: xhr.getResponseHeader('content-type')
  367. });
  368. };
  369. xhr.send();
  370. });
  371. },
  372. _setXHR(xhr
  373. /*: any*/
  374. ) {
  375. XHR = xhr;
  376. }
  377. };
  378. CoreManager.setFileController(DefaultController);
  379. export default ParseFile;