managed-upload.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. const fs = require('fs');
  2. const is = require('is-type-of');
  3. const util = require('util');
  4. const path = require('path');
  5. const mime = require('mime');
  6. const { isFile } = require('./common/utils/isFile');
  7. const { isArray } = require('./common/utils/isArray');
  8. const { isBuffer } = require('./common/utils/isBuffer');
  9. const proto = exports;
  10. /**
  11. * Multipart operations
  12. */
  13. /**
  14. * Upload a file to OSS using multipart uploads
  15. * @param {String} name
  16. * @param {String|File|Buffer} file
  17. * @param {Object} options
  18. * {Object} options.callback The callback parameter is composed of a JSON string encoded in Base64
  19. * {String} options.callback.url the OSS sends a callback request to this URL
  20. * {String} options.callback.host The host header value for initiating callback requests
  21. * {String} options.callback.body The value of the request body when a callback is initiated
  22. * {String} options.callback.contentType The Content-Type of the callback requests initiatiated
  23. * {Object} options.callback.customValue Custom parameters are a map of key-values, e.g:
  24. * customValue = {
  25. * key1: 'value1',
  26. * key2: 'value2'
  27. * }
  28. */
  29. proto.multipartUpload = async function multipartUpload(name, file, options) {
  30. this.resetCancelFlag();
  31. options = options || {};
  32. if (options.checkpoint && options.checkpoint.uploadId) {
  33. return await this._resumeMultipart(options.checkpoint, options);
  34. }
  35. const minPartSize = 100 * 1024;
  36. if (!options.mime) {
  37. if (isFile(file)) {
  38. options.mime = mime.getType(path.extname(file.name));
  39. } else if (isBuffer(file)) {
  40. options.mime = '';
  41. } else {
  42. options.mime = mime.getType(path.extname(file));
  43. }
  44. }
  45. options.headers = options.headers || {};
  46. this._convertMetaToHeaders(options.meta, options.headers);
  47. const fileSize = await this._getFileSize(file);
  48. if (fileSize < minPartSize) {
  49. const stream = this._createStream(file, 0, fileSize);
  50. options.contentLength = fileSize;
  51. const result = await this.putStream(name, stream, options);
  52. if (options && options.progress) {
  53. await options.progress(1);
  54. }
  55. const ret = {
  56. res: result.res,
  57. bucket: this.options.bucket,
  58. name,
  59. etag: result.res.headers.etag
  60. };
  61. if ((options.headers && options.headers['x-oss-callback']) || options.callback) {
  62. ret.data = result.data;
  63. }
  64. return ret;
  65. }
  66. if (options.partSize && !(parseInt(options.partSize, 10) === options.partSize)) {
  67. throw new Error('partSize must be int number');
  68. }
  69. if (options.partSize && options.partSize < minPartSize) {
  70. throw new Error(`partSize must not be smaller than ${minPartSize}`);
  71. }
  72. const initResult = await this.initMultipartUpload(name, options);
  73. const { uploadId } = initResult;
  74. const partSize = this._getPartSize(fileSize, options.partSize);
  75. const checkpoint = {
  76. file,
  77. name,
  78. fileSize,
  79. partSize,
  80. uploadId,
  81. doneParts: []
  82. };
  83. if (options && options.progress) {
  84. await options.progress(0, checkpoint, initResult.res);
  85. }
  86. return await this._resumeMultipart(checkpoint, options);
  87. };
  88. /*
  89. * Resume multipart upload from checkpoint. The checkpoint will be
  90. * updated after each successful part upload.
  91. * @param {Object} checkpoint the checkpoint
  92. * @param {Object} options
  93. */
  94. proto._resumeMultipart = async function _resumeMultipart(checkpoint, options) {
  95. if (this.isCancel()) {
  96. throw this._makeCancelEvent();
  97. }
  98. const {
  99. file, fileSize, partSize, uploadId, doneParts, name
  100. } = checkpoint;
  101. const partOffs = this._divideParts(fileSize, partSize);
  102. const numParts = partOffs.length;
  103. let uploadPartJob = function uploadPartJob(self, partNo) {
  104. // eslint-disable-next-line no-async-promise-executor
  105. return new Promise(async (resolve, reject) => {
  106. try {
  107. if (!self.isCancel()) {
  108. const pi = partOffs[partNo - 1];
  109. const stream = self._createStream(file, pi.start, pi.end);
  110. const data = {
  111. stream,
  112. size: pi.end - pi.start
  113. };
  114. if (isArray(self.multipartUploadStreams)) {
  115. self.multipartUploadStreams.push(data.stream);
  116. } else {
  117. self.multipartUploadStreams = [data.stream];
  118. }
  119. const removeStreamFromMultipartUploadStreams = function () {
  120. if (!stream.destroyed) {
  121. stream.destroy();
  122. }
  123. const index = self.multipartUploadStreams.indexOf(stream);
  124. if (index !== -1) {
  125. self.multipartUploadStreams.splice(index, 1);
  126. }
  127. };
  128. stream.on('close', removeStreamFromMultipartUploadStreams);
  129. stream.on('error', removeStreamFromMultipartUploadStreams);
  130. let result;
  131. try {
  132. result = await self._uploadPart(name, uploadId, partNo, data);
  133. } catch (error) {
  134. removeStreamFromMultipartUploadStreams();
  135. if (error.status === 404) {
  136. throw self._makeAbortEvent();
  137. }
  138. throw error;
  139. }
  140. if (!self.isCancel()) {
  141. doneParts.push({
  142. number: partNo,
  143. etag: result.res.headers.etag
  144. });
  145. checkpoint.doneParts = doneParts;
  146. if (options.progress) {
  147. await options.progress(doneParts.length / numParts, checkpoint, result.res);
  148. }
  149. }
  150. }
  151. resolve();
  152. } catch (err) {
  153. err.partNum = partNo;
  154. reject(err);
  155. }
  156. });
  157. };
  158. const all = Array.from(new Array(numParts), (x, i) => i + 1);
  159. const done = doneParts.map(p => p.number);
  160. const todo = all.filter(p => done.indexOf(p) < 0);
  161. const defaultParallel = 5;
  162. const parallel = options.parallel || defaultParallel;
  163. if (this.checkBrowserAndVersion('Internet Explorer', '10') || parallel === 1) {
  164. for (let i = 0; i < todo.length; i++) {
  165. if (this.isCancel()) {
  166. throw this._makeCancelEvent();
  167. }
  168. /* eslint no-await-in-loop: [0] */
  169. await uploadPartJob(this, todo[i]);
  170. }
  171. } else {
  172. // upload in parallel
  173. const jobErr = await this._parallelNode(todo, parallel, uploadPartJob);
  174. const abortEvent = jobErr.find(err => err.name === 'abort');
  175. if (abortEvent) throw abortEvent;
  176. if (this.isCancel()) {
  177. uploadPartJob = null;
  178. throw this._makeCancelEvent();
  179. }
  180. if (jobErr && jobErr.length > 0) {
  181. jobErr[0].message = `Failed to upload some parts with error: ${jobErr[0].toString()} part_num: ${jobErr[0].partNum}`;
  182. throw jobErr[0];
  183. }
  184. }
  185. return await this.completeMultipartUpload(name, uploadId, doneParts, options);
  186. };
  187. /**
  188. * Get file size
  189. */
  190. proto._getFileSize = async function _getFileSize(file) {
  191. if (isBuffer(file)) {
  192. return file.length;
  193. } else if (isFile(file)) {
  194. return file.size;
  195. } if (is.string(file)) {
  196. const stat = await this._statFile(file);
  197. return stat.size;
  198. }
  199. throw new Error('_getFileSize requires Buffer/File/String.');
  200. };
  201. /*
  202. * Readable stream for Web File
  203. */
  204. const { Readable } = require('stream');
  205. function WebFileReadStream(file, options) {
  206. if (!(this instanceof WebFileReadStream)) {
  207. return new WebFileReadStream(file, options);
  208. }
  209. Readable.call(this, options);
  210. this.file = file;
  211. this.reader = new FileReader();
  212. this.start = 0;
  213. this.finish = false;
  214. this.fileBuffer = null;
  215. }
  216. util.inherits(WebFileReadStream, Readable);
  217. WebFileReadStream.prototype.readFileAndPush = function readFileAndPush(size) {
  218. if (this.fileBuffer) {
  219. let pushRet = true;
  220. while (pushRet && this.fileBuffer && this.start < this.fileBuffer.length) {
  221. const { start } = this;
  222. let end = start + size;
  223. end = end > this.fileBuffer.length ? this.fileBuffer.length : end;
  224. this.start = end;
  225. pushRet = this.push(this.fileBuffer.slice(start, end));
  226. }
  227. }
  228. };
  229. WebFileReadStream.prototype._read = function _read(size) {
  230. if ((this.file && this.start >= this.file.size) ||
  231. (this.fileBuffer && this.start >= this.fileBuffer.length) ||
  232. (this.finish) || (this.start === 0 && !this.file)) {
  233. if (!this.finish) {
  234. this.fileBuffer = null;
  235. this.finish = true;
  236. }
  237. this.push(null);
  238. return;
  239. }
  240. const defaultReadSize = 16 * 1024;
  241. size = size || defaultReadSize;
  242. const that = this;
  243. this.reader.onload = function (e) {
  244. that.fileBuffer = Buffer.from(new Uint8Array(e.target.result));
  245. that.file = null;
  246. that.readFileAndPush(size);
  247. };
  248. this.reader.onerror = function onload(e) {
  249. const error = e.srcElement && e.srcElement.error;
  250. if (error) {
  251. throw error;
  252. }
  253. throw e;
  254. };
  255. if (this.start === 0) {
  256. this.reader.readAsArrayBuffer(this.file);
  257. } else {
  258. this.readFileAndPush(size);
  259. }
  260. };
  261. proto._createStream = function _createStream(file, start, end) {
  262. if (is.readableStream(file)) {
  263. return file;
  264. } else if (isFile(file)) {
  265. return new WebFileReadStream(file.slice(start, end));
  266. } else if (isBuffer(file)) {
  267. const iterable = file.subarray(start, end);
  268. // we can't use Readable.from() since it is only support in Node v10
  269. return new Readable({
  270. read() {
  271. this.push(iterable);
  272. this.push(null);
  273. }
  274. });
  275. } else if (is.string(file)) {
  276. return fs.createReadStream(file, {
  277. start,
  278. end: end - 1
  279. });
  280. }
  281. throw new Error('_createStream requires Buffer/File/String.');
  282. };
  283. proto._getPartSize = function _getPartSize(fileSize, partSize) {
  284. const maxNumParts = 10 * 1000;
  285. const defaultPartSize = 1 * 1024 * 1024;
  286. if (!partSize) partSize = defaultPartSize;
  287. const safeSize = Math.ceil(fileSize / maxNumParts);
  288. if (partSize < safeSize) {
  289. partSize = safeSize;
  290. console.warn(`partSize has been set to ${partSize}, because the partSize you provided causes partNumber to be greater than 10,000`);
  291. }
  292. return partSize;
  293. };
  294. proto._divideParts = function _divideParts(fileSize, partSize) {
  295. const numParts = Math.ceil(fileSize / partSize);
  296. const partOffs = [];
  297. for (let i = 0; i < numParts; i++) {
  298. const start = partSize * i;
  299. const end = Math.min(start + partSize, fileSize);
  300. partOffs.push({
  301. start,
  302. end
  303. });
  304. }
  305. return partOffs;
  306. };