xhrFileTransfer.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /*
  2. *
  3. * Licensed to the Apache Software Foundation (ASF) under one
  4. * or more contributor license agreements. See the NOTICE file
  5. * distributed with this work for additional information
  6. * regarding copyright ownership. The ASF licenses this file
  7. * to you under the Apache License, Version 2.0 (the
  8. * "License"); you may not use this file except in compliance
  9. * with the License. You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing,
  14. * software distributed under the License is distributed on an
  15. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. * KIND, either express or implied. See the License for the
  17. * specific language governing permissions and limitations
  18. * under the License.
  19. *
  20. */
  21. /* global Blob:false */
  22. var cordova = require('cordova'),
  23. resolve = cordova.require('cordova-plugin-file.resolveLocalFileSystemURIProxy'),
  24. requestAnimationFrame = cordova.require('cordova-plugin-file.bb10RequestAnimationFrame'),
  25. xhr = {};
  26. function getParentPath(filePath) {
  27. var pos = filePath.lastIndexOf('/');
  28. return filePath.substring(0, pos + 1);
  29. }
  30. function getFileName(filePath) {
  31. var pos = filePath.lastIndexOf('/');
  32. return filePath.substring(pos + 1);
  33. }
  34. function checkURL(url) {
  35. return url.indexOf(' ') === -1 ? true : false;
  36. }
  37. module.exports = {
  38. abort: function (win, fail, args) {
  39. var id = args[0];
  40. if (xhr[id]) {
  41. xhr[id].abort();
  42. if (typeof(win) === 'function') {
  43. win();
  44. }
  45. } else if (typeof(fail) === 'function') {
  46. fail();
  47. }
  48. },
  49. upload: function(win, fail, args) {
  50. var filePath = args[0],
  51. server = args[1],
  52. fileKey = args[2],
  53. fileName = args[3],
  54. mimeType = args[4],
  55. params = args[5],
  56. /*trustAllHosts = args[6],*/
  57. chunkedMode = args[7],
  58. headers = args[8],
  59. onSuccess = function (data) {
  60. if (typeof(win) === 'function') {
  61. win(data);
  62. }
  63. },
  64. onFail = function (code) {
  65. delete xhr[fileKey];
  66. if (typeof(fail) === 'function') {
  67. fail(code);
  68. }
  69. };
  70. if (!checkURL(server)) {
  71. onFail(new FileTransferError(FileTransferError.INVALID_URL_ERR, server, filePath));
  72. }
  73. xhr[fileKey] = new XMLHttpRequest();
  74. xhr[fileKey].onabort = function () {
  75. onFail(new FileTransferError(FileTransferError.ABORT_ERR, server, filePath, this.status, xhr[fileKey].response));
  76. };
  77. resolve(function(entry) {
  78. requestAnimationFrame(function () {
  79. entry.nativeEntry.file(function(file) {
  80. function uploadFile(blobFile) {
  81. var fd = new FormData();
  82. fd.append(fileKey, blobFile, fileName);
  83. for (var prop in params) {
  84. if(params.hasOwnProperty(prop)) {
  85. fd.append(prop, params[prop]);
  86. }
  87. }
  88. xhr[fileKey].open("POST", server);
  89. xhr[fileKey].onload = function(evt) {
  90. if (xhr[fileKey].status === 200) {
  91. var result = new FileUploadResult();
  92. result.bytesSent = file.size;
  93. result.responseCode = xhr[fileKey].status;
  94. result.response = xhr[fileKey].response;
  95. delete xhr[fileKey];
  96. onSuccess(result);
  97. } else if (xhr[fileKey].status === 404) {
  98. onFail(new FileTransferError(FileTransferError.INVALID_URL_ERR, server, filePath, xhr[fileKey].status, xhr[fileKey].response));
  99. } else {
  100. onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, server, filePath, xhr[fileKey].status, xhr[fileKey].response));
  101. }
  102. };
  103. xhr[fileKey].ontimeout = function(evt) {
  104. onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, server, filePath, xhr[fileKey].status, xhr[fileKey].response));
  105. };
  106. xhr[fileKey].onerror = function () {
  107. onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, server, filePath, this.status, xhr[fileKey].response));
  108. };
  109. xhr[fileKey].upload.onprogress = function (evt) {
  110. if (evt.loaded > 0) {
  111. onSuccess(evt);
  112. }
  113. };
  114. for (var header in headers) {
  115. if (headers.hasOwnProperty(header)) {
  116. xhr[fileKey].setRequestHeader(header, headers[header]);
  117. }
  118. }
  119. requestAnimationFrame(function () {
  120. xhr[fileKey].send(fd);
  121. });
  122. }
  123. var bytesPerChunk;
  124. if (chunkedMode === true) {
  125. bytesPerChunk = 1024 * 1024; // 1MB chunk sizes.
  126. } else {
  127. bytesPerChunk = file.size;
  128. }
  129. var start = 0;
  130. var end = bytesPerChunk;
  131. while (start < file.size) {
  132. var chunk = file.slice(start, end, mimeType);
  133. uploadFile(chunk);
  134. start = end;
  135. end = start + bytesPerChunk;
  136. }
  137. }, function(error) {
  138. onFail(new FileTransferError(FileTransferError.FILE_NOT_FOUND_ERR, server, filePath));
  139. });
  140. });
  141. }, function(error) {
  142. onFail(new FileTransferError(FileTransferError.FILE_NOT_FOUND_ERR, server, filePath));
  143. }, [filePath]);
  144. },
  145. download: function (win, fail, args) {
  146. var source = args[0],
  147. target = args[1],
  148. id = args[3],
  149. headers = args[4],
  150. fileWriter,
  151. onSuccess = function (entry) {
  152. if (typeof(win) === 'function') {
  153. win(entry);
  154. }
  155. },
  156. onFail = function (error) {
  157. var reader;
  158. delete xhr[id];
  159. if (typeof(fail) === 'function') {
  160. if (error && error.body && typeof(error.body) === 'object') {
  161. reader = new FileReader()._realReader;
  162. reader.onloadend = function () {
  163. error.body = this.result;
  164. fail(error);
  165. };
  166. reader.onerror = function () {
  167. fail(error);
  168. };
  169. reader.readAsText(error.body);
  170. } else {
  171. fail(error);
  172. }
  173. }
  174. };
  175. if (!checkURL(source)) {
  176. onFail(new FileTransferError(FileTransferError.INVALID_URL_ERR, source, target));
  177. }
  178. xhr[id] = new XMLHttpRequest();
  179. function writeFile(entry) {
  180. entry.createWriter(function (writer) {
  181. fileWriter = writer;
  182. fileWriter.onwriteend = function (evt) {
  183. if (!evt.target.error) {
  184. entry.filesystemName = entry.filesystem.name;
  185. delete xhr[id];
  186. onSuccess(entry);
  187. } else {
  188. onFail(evt.target.error);
  189. }
  190. };
  191. fileWriter.onerror = function (evt) {
  192. onFail(evt.target.error);
  193. };
  194. fileWriter.write(new Blob([xhr[id].response]));
  195. }, function (error) {
  196. onFail(error);
  197. });
  198. }
  199. xhr[id].onerror = function (e) {
  200. onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, source, target, xhr[id].status, xhr[id].response));
  201. };
  202. xhr[id].onabort = function (e) {
  203. onFail(new FileTransferError(FileTransferError.ABORT_ERR, source, target, xhr[id].status, xhr[id].response));
  204. };
  205. xhr[id].onload = function () {
  206. if (xhr[id].readyState === xhr[id].DONE) {
  207. if (xhr[id].status === 200 && xhr[id].response) {
  208. resolveLocalFileSystemURI(getParentPath(target), function (dir) {
  209. dir.getFile(getFileName(target), {create: true}, writeFile, function (error) {
  210. onFail(new FileTransferError(FileTransferError.FILE_NOT_FOUND_ERR, source, target, xhr[id].status, xhr[id].response));
  211. });
  212. }, function (error) {
  213. onFail(new FileTransferError(FileTransferError.FILE_NOT_FOUND_ERR, source, target, xhr[id].status, xhr[id].response));
  214. });
  215. } else if (xhr[id].status === 404) {
  216. onFail(new FileTransferError(FileTransferError.INVALID_URL_ERR, source, target, xhr[id].status, xhr[id].response));
  217. } else {
  218. onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, source, target, xhr[id].status, xhr[id].response));
  219. }
  220. }
  221. };
  222. xhr[id].onprogress = function (evt) {
  223. onSuccess(evt);
  224. };
  225. xhr[id].open("GET", source, true);
  226. for (var header in headers) {
  227. if (headers.hasOwnProperty(header)) {
  228. xhr[id].setRequestHeader(header, headers[header]);
  229. }
  230. }
  231. xhr[id].responseType = "blob";
  232. requestAnimationFrame(function () {
  233. if (xhr[id]) {
  234. xhr[id].send();
  235. }
  236. });
  237. }
  238. };