You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ObsUploader.vue 15 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. <template>
  2. <div class="dropzone-wrapper dataset-files">
  3. <div
  4. id="dataset"
  5. class="dropzone"
  6. />
  7. <p class="upload-info">
  8. {{ file_status_text }}
  9. <span class="success">{{ status }}</span>
  10. </p>
  11. <p>云脑1提供 <span class="text blue">CPU / GPU</span> 资源,云脑2提供 <span class="text blue">Ascend NPU</span> 资源;调试使用的数据集也需要上传到对应的环境。</p>
  12. </div>
  13. </template>
  14. <script>
  15. /* eslint-disable eqeqeq */
  16. // import Dropzone from 'dropzone/dist/dropzone.js';
  17. // import 'dropzone/dist/dropzone.css'
  18. import SparkMD5 from 'spark-md5';
  19. import axios from 'axios';
  20. import qs from 'qs';
  21. import createDropzone from '../features/dropzone.js';
  22. const {_AppSubUrl, _StaticUrlPrefix, csrf} = window.config;
  23. const CloudBrainType = 1;
  24. export default {
  25. data() {
  26. return {
  27. dropzoneUploader: null,
  28. maxFiles: 1,
  29. maxFilesize: 1 * 1024 * 1024 * 1024 * 1024,
  30. acceptedFiles: '*/*',
  31. progress: 0,
  32. status: '',
  33. dropzoneParams: {},
  34. file_status_text: ''
  35. };
  36. },
  37. async mounted() {
  38. this.dropzoneParams = $('div#minioUploader-params');
  39. this.file_status_text = this.dropzoneParams.data('file-status');
  40. this.status = this.dropzoneParams.data('file-init-status');
  41. let previewTemplate = '';
  42. previewTemplate += '<div class="dz-preview dz-file-preview">\n ';
  43. previewTemplate += ' <div class="dz-details">\n ';
  44. previewTemplate += ' <div class="dz-filename">';
  45. previewTemplate +=
  46. ' <span data-dz-name data-dz-thumbnail></span>';
  47. previewTemplate += ' </div>\n ';
  48. previewTemplate += ' <div class="dz-size" data-dz-size></div>\n ';
  49. previewTemplate += ' </div>\n ';
  50. previewTemplate += ' <div class="dz-progress ui active progress">';
  51. previewTemplate +=
  52. ' <div class="dz-upload bar" data-dz-uploadprogress><div class="progress"></div></div>\n ';
  53. previewTemplate += ' </div>\n ';
  54. previewTemplate += ' <div class="dz-success-mark">';
  55. previewTemplate += ' <span>上传成功</span>';
  56. previewTemplate += ' </div>\n ';
  57. previewTemplate += ' <div class="dz-error-mark">';
  58. previewTemplate += ' <span>上传失败</span>';
  59. previewTemplate += ' </div>\n ';
  60. previewTemplate += ' <div class="dz-error-message">';
  61. previewTemplate += ' <span data-dz-errormessage></span>';
  62. previewTemplate += ' </div>\n';
  63. previewTemplate += '</div>';
  64. const $dropzone = $('div#dataset');
  65. console.log('createDropzone');
  66. const dropzoneUploader = await createDropzone($dropzone[0], {
  67. url: '/todouploader',
  68. maxFiles: this.maxFiles,
  69. maxFilesize: this.maxFileSize,
  70. timeout: 0,
  71. autoQueue: false,
  72. dictDefaultMessage: this.dropzoneParams.data('default-message'),
  73. dictInvalidFileType: this.dropzoneParams.data('invalid-input-type'),
  74. dictFileTooBig: this.dropzoneParams.data('file-too-big'),
  75. dictRemoveFile: this.dropzoneParams.data('remove-file'),
  76. previewTemplate
  77. });
  78. dropzoneUploader.on('addedfile', (file) => {
  79. setTimeout(() => {
  80. // eslint-disable-next-line no-unused-expressions
  81. file.accepted && this.onFileAdded(file);
  82. }, 200);
  83. });
  84. dropzoneUploader.on('maxfilesexceeded', function (file) {
  85. if (this.files[0].status !== 'success') {
  86. alert(this.dropzoneParams.data('waitting-uploading'));
  87. this.removeFile(file);
  88. return;
  89. }
  90. this.removeAllFiles();
  91. this.addFile(file);
  92. });
  93. this.dropzoneUploader = dropzoneUploader;
  94. },
  95. methods: {
  96. resetStatus() {
  97. this.progress = 0;
  98. this.status = '';
  99. },
  100. updateProgress(file, progress) {
  101. file.previewTemplate.querySelector(
  102. '.dz-upload'
  103. ).style.width = `${progress}%`;
  104. },
  105. emitDropzoneSuccess(file) {
  106. file.status = 'success';
  107. this.dropzoneUploader.emit('success', file);
  108. this.dropzoneUploader.emit('complete', file);
  109. },
  110. emitDropzoneFailed(file) {
  111. this.status = this.dropzoneParams.data('falied');
  112. file.status = 'error';
  113. this.dropzoneUploader.emit('error', file);
  114. // this.dropzoneUploader.emit('complete', file);
  115. },
  116. onFileAdded(file) {
  117. file.datasetId = document
  118. .getElementById('datasetId')
  119. .getAttribute('datasetId');
  120. this.resetStatus();
  121. this.computeMD5(file);
  122. },
  123. finishUpload(file) {
  124. this.emitDropzoneSuccess(file);
  125. setTimeout(() => {
  126. window.location.reload();
  127. }, 1000);
  128. },
  129. computeMD5(file) {
  130. this.resetStatus();
  131. const blobSlice =
  132. File.prototype.slice ||
  133. File.prototype.mozSlice ||
  134. File.prototype.webkitSlice,
  135. chunkSize = 1024 * 1024 * 64,
  136. chunks = Math.ceil(file.size / chunkSize),
  137. spark = new SparkMD5.ArrayBuffer(),
  138. fileReader = new FileReader();
  139. let currentChunk = 0;
  140. const time = new Date().getTime();
  141. // console.log('计算MD5...')
  142. this.status = this.dropzoneParams.data('md5-computing');
  143. file.totalChunkCounts = chunks;
  144. loadNext();
  145. fileReader.onload = (e) => {
  146. fileLoaded.call(this, e);
  147. };
  148. fileReader.onerror = (err) => {
  149. console.warn('oops, something went wrong.', err);
  150. file.cancel();
  151. };
  152. function fileLoaded(e) {
  153. spark.append(e.target.result); // Append array buffer
  154. currentChunk++;
  155. if (currentChunk < chunks) {
  156. // console.log(`第${currentChunk}分片解析完成, 开始第${currentChunk +1}/${chunks}分片解析`);
  157. this.status = `${this.dropzoneParams.data('loading-file')} ${(
  158. (currentChunk / chunks) *
  159. 100
  160. ).toFixed(2)}% (${currentChunk}/${chunks})`;
  161. this.updateProgress(file, ((currentChunk / chunks) * 100).toFixed(2));
  162. loadNext();
  163. return;
  164. }
  165. const md5 = spark.end();
  166. console.log(
  167. `MD5计算完成:${file.name} \nMD5:${md5} \n分片:${chunks} 大小:${
  168. file.size
  169. } 用时:${(new Date().getTime() - time) / 1000} s`
  170. );
  171. spark.destroy(); // 释放缓存
  172. file.uniqueIdentifier = md5; // 将文件md5赋值给文件唯一标识
  173. file.cmd5 = false; // 取消计算md5状态
  174. this.computeMD5Success(file);
  175. }
  176. function loadNext() {
  177. const start = currentChunk * chunkSize;
  178. const end =
  179. start + chunkSize >= file.size ? file.size : start + chunkSize;
  180. fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
  181. }
  182. },
  183. async computeMD5Success(md5edFile) {
  184. const file = await this.getSuccessChunks(md5edFile);
  185. try {
  186. if (file.uploadID == '' || file.uuid == '') {
  187. // 未上传过
  188. await this.newMultiUpload(file);
  189. if (file.uploadID != '' && file.uuid != '') {
  190. file.chunks = '';
  191. this.multipartUpload(file);
  192. } else {
  193. // 失败如何处理
  194. return;
  195. }
  196. return;
  197. }
  198. if (file.uploaded == '1') {
  199. // 已上传成功
  200. // 秒传
  201. if (file.attachID == '0') {
  202. // 删除数据集记录,未删除文件
  203. await addAttachment(file);
  204. }
  205. //不同数据集上传同一个文件
  206. if (file.datasetID != '') {
  207. if (Number(file.datasetID) != file.datasetId) {
  208. var info = "该文件已上传,对应数据集(" + file.datasetName + ")-文件(" + file.realName + ")";
  209. window.alert(info);
  210. window.location.reload();
  211. }
  212. }
  213. console.log('文件已上传完成');
  214. this.progress = 100;
  215. this.status = this.dropzoneParams.data('upload-complete');
  216. this.finishUpload(file);
  217. } else {
  218. // 断点续传
  219. this.multipartUpload(file);
  220. }
  221. } catch (error) {
  222. this.emitDropzoneFailed(file);
  223. console.log(error);
  224. }
  225. async function addAttachment(file) {
  226. return await axios.post(
  227. '/attachments/add',
  228. qs.stringify({
  229. uuid: file.uuid,
  230. file_name: file.name,
  231. size: file.size,
  232. dataset_id: file.datasetId,
  233. type: CloudBrainType,
  234. _csrf: csrf,
  235. })
  236. );
  237. }
  238. },
  239. async getSuccessChunks(file) {
  240. const params = {
  241. params: {
  242. md5: file.uniqueIdentifier,
  243. type: CloudBrainType,
  244. _csrf: csrf
  245. }
  246. };
  247. try {
  248. const response = await axios.get('/attachments/get_chunks', params);
  249. file.uploadID = response.data.uploadID;
  250. file.uuid = response.data.uuid;
  251. file.uploaded = response.data.uploaded;
  252. file.chunks = response.data.chunks;
  253. file.attachID = response.data.attachID;
  254. file.datasetID = response.data.datasetID;
  255. file.datasetName = response.data.datasetName;
  256. file.realName = response.data.fileName;
  257. return file;
  258. } catch (error) {
  259. this.emitDropzoneFailed(file);
  260. console.log('getSuccessChunks catch: ', error);
  261. return null;
  262. }
  263. },
  264. async newMultiUpload(file) {
  265. const res = await axios.get('/attachments/new_multipart', {
  266. params: {
  267. totalChunkCounts: file.totalChunkCounts,
  268. md5: file.uniqueIdentifier,
  269. size: file.size,
  270. fileType: file.type,
  271. type: CloudBrainType,
  272. file_name: file.name,
  273. _csrf: csrf
  274. }
  275. });
  276. file.uploadID = res.data.uploadID;
  277. file.uuid = res.data.uuid;
  278. },
  279. multipartUpload(file) {
  280. const blobSlice =
  281. File.prototype.slice ||
  282. File.prototype.mozSlice ||
  283. File.prototype.webkitSlice,
  284. chunkSize = 1024 * 1024 * 64,
  285. chunks = Math.ceil(file.size / chunkSize),
  286. fileReader = new FileReader(),
  287. time = new Date().getTime();
  288. let currentChunk = 0;
  289. function loadNext() {
  290. const start = currentChunk * chunkSize;
  291. const end =
  292. start + chunkSize >= file.size ? file.size : start + chunkSize;
  293. fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
  294. }
  295. function checkSuccessChunks() {
  296. const index = successChunks.indexOf((currentChunk + 1).toString());
  297. if (index == -1) {
  298. return false;
  299. }
  300. return true;
  301. }
  302. async function getUploadChunkUrl(currentChunk, partSize) {
  303. const res = await axios.get('/attachments/get_multipart_url', {
  304. params: {
  305. uuid: file.uuid,
  306. uploadID: file.uploadID,
  307. size: partSize,
  308. chunkNumber: currentChunk + 1,
  309. type: CloudBrainType,
  310. file_name: file.name,
  311. _csrf: csrf
  312. }
  313. });
  314. urls[currentChunk] = res.data.url;
  315. }
  316. async function uploadMinio(url, e) {
  317. let urls = [];
  318. const res = await axios.put(url, e.target.result, {
  319. headers: {
  320. 'Content-Type': ''
  321. }});
  322. etags[currentChunk] = res.headers.etag;
  323. }
  324. async function updateChunk(currentChunk) {
  325. await axios.post(
  326. '/attachments/update_chunk',
  327. qs.stringify({
  328. uuid: file.uuid,
  329. chunkNumber: currentChunk + 1,
  330. etag: etags[currentChunk],
  331. type: CloudBrainType,
  332. _csrf: csrf
  333. })
  334. );
  335. }
  336. async function uploadChunk(e) {
  337. try {
  338. if (!checkSuccessChunks()) {
  339. const start = currentChunk * chunkSize;
  340. const partSize =
  341. start + chunkSize >= file.size ? file.size - start : chunkSize;
  342. // 获取分片上传url
  343. await getUploadChunkUrl(currentChunk, partSize);
  344. if (urls[currentChunk] != '') {
  345. // 上传到minio
  346. await uploadMinio(urls[currentChunk], e);
  347. if (etags[currentChunk] != '') {
  348. // 更新数据库:分片上传结果
  349. //await updateChunk(currentChunk);
  350. } else {
  351. console.log("上传到minio uploadChunk etags[currentChunk] == ''");// TODO
  352. }
  353. } else {
  354. console.log("uploadChunk urls[currentChunk] != ''");// TODO
  355. }
  356. }
  357. } catch (error) {
  358. this.emitDropzoneFailed(file);
  359. console.log(error);
  360. }
  361. }
  362. async function completeUpload() {
  363. return await axios.post(
  364. '/attachments/complete_multipart',
  365. qs.stringify({
  366. uuid: file.uuid,
  367. uploadID: file.uploadID,
  368. file_name: file.name,
  369. size: file.size,
  370. dataset_id: file.datasetId,
  371. type: CloudBrainType,
  372. _csrf: csrf
  373. })
  374. );
  375. }
  376. const successChunks = [];
  377. let successParts = [];
  378. successParts = file.chunks.split(',');
  379. for (let i = 0; i < successParts.length; i++) {
  380. successChunks[i] = successParts[i].split('-')[0];
  381. }
  382. const urls = []; // TODO const ?
  383. const etags = [];
  384. console.log('上传分片...');
  385. this.status = this.dropzoneParams.data('uploading');
  386. loadNext();
  387. fileReader.onload = async (e) => {
  388. await uploadChunk(e);
  389. fileReader.abort();
  390. currentChunk++;
  391. if (currentChunk < chunks) {
  392. console.log(
  393. `第${currentChunk}个分片上传完成, 开始第${currentChunk +
  394. 1}/${chunks}个分片上传`
  395. );
  396. this.progress = Math.ceil((currentChunk / chunks) * 100);
  397. this.updateProgress(file, ((currentChunk / chunks) * 100).toFixed(2));
  398. this.status = `${this.dropzoneParams.data('uploading')} ${(
  399. (currentChunk / chunks) *
  400. 100
  401. ).toFixed(2)}%`;
  402. await loadNext();
  403. } else {
  404. await completeUpload();
  405. console.log(
  406. `文件上传完成:${file.name} \n分片:${chunks} 大小:${
  407. file.size
  408. } 用时:${(new Date().getTime() - time) / 1000} s`
  409. );
  410. this.progress = 100;
  411. this.status = this.dropzoneParams.data('upload-complete');
  412. this.finishUpload(file);
  413. }
  414. };
  415. }
  416. }
  417. };
  418. </script>
  419. <style>
  420. .dropzone-wrapper {
  421. margin: 2em auto;
  422. }
  423. .ui .dropzone {
  424. border: 2px dashed #0087f5;
  425. box-shadow: none !important;
  426. padding: 0;
  427. min-height: 5rem;
  428. border-radius: 4px;
  429. }
  430. .dataset .dataset-files #dataset .dz-preview.dz-file-preview,
  431. .dataset .dataset-files #dataset .dz-preview.dz-processing {
  432. display: flex;
  433. align-items: center;
  434. }
  435. .dataset .dataset-files #dataset .dz-preview {
  436. border-bottom: 1px solid #dadce0;
  437. min-height: 0;
  438. }
  439. </style>