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.

MinioUploader.vue 18 kB

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