managed-upload.js 10 KB

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