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