用工小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

381 lines
11 KiB

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