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
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. 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. },
  134. updateProgress(file, progress) {
  135. console.log("progress---",progress)
  136. file.previewTemplate.querySelector(
  137. '.dz-upload'
  138. ).style.width = `${progress}%`
  139. file.previewTemplate.querySelector(
  140. '.dz-upload'
  141. ).style.background = '#409eff';
  142. },
  143. emitDropzoneSuccess(file) {
  144. file.status = 'success';
  145. this.dropzoneUploader.emit('success', file);
  146. this.dropzoneUploader.emit('complete', file);
  147. },
  148. emitDropzoneFailed(file) {
  149. this.status = this.dropzoneParams.data('falied');
  150. file.status = 'error';
  151. this.dropzoneUploader.emit('error', file);
  152. // this.dropzoneUploader.emit('complete', file);
  153. },
  154. onFileAdded() {
  155. this.btnFlag = true
  156. this.file.datasetId = document
  157. .getElementById('datasetId')
  158. .getAttribute('datasetId');
  159. this.resetStatus();
  160. if(!this.file?.upload){
  161. this.btnFlag = false
  162. return
  163. }
  164. this.computeMD5(this.file);
  165. },
  166. finishUpload(file) {
  167. this.emitDropzoneSuccess(file);
  168. setTimeout(() => {
  169. window.location.href = this.repoPath
  170. }, 1000);
  171. },
  172. computeMD5(file) {
  173. this.resetStatus();
  174. const blobSlice =
  175. File.prototype.slice ||
  176. File.prototype.mozSlice ||
  177. File.prototype.webkitSlice,
  178. //chunkSize = 1024 * 1024 * 64,
  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. // console.log('计算MD5...')
  185. this.status = this.dropzoneParams.data('md5-computing');
  186. file.totalChunkCounts = chunks;
  187. loadNext();
  188. fileReader.onload = (e) => {
  189. fileLoaded.call(this, e);
  190. };
  191. fileReader.onerror = (err) => {
  192. console.warn('oops, something went wrong.', err);
  193. file.cancel();
  194. };
  195. function fileLoaded(e) {
  196. spark.append(e.target.result); // Append array buffer
  197. currentChunk++;
  198. if (currentChunk < chunks) {
  199. // console.log(`第${currentChunk}分片解析完成, 开始第${currentChunk +1}/${chunks}分片解析`);
  200. this.status = `${this.dropzoneParams.data('loading-file')} ${(
  201. (currentChunk / chunks) *
  202. 100
  203. ).toFixed(2)}% (${currentChunk}/${chunks})`;
  204. this.updateProgress(file, ((currentChunk / chunks) * 100).toFixed(2));
  205. loadNext();
  206. return;
  207. }
  208. const md5 = spark.end();
  209. console.log(
  210. `MD5计算完成:${file.name} \nMD5:${md5} \n分片:${chunks} 大小:${
  211. file.size
  212. } 用时:${(new Date().getTime() - time) / 1000} s`
  213. );
  214. spark.destroy(); // 释放缓存
  215. file.uniqueIdentifier = md5; // 将文件md5赋值给文件唯一标识
  216. file.cmd5 = false; // 取消计算md5状态
  217. this.computeMD5Success(file);
  218. }
  219. function loadNext() {
  220. const start = currentChunk * chunkSize;
  221. const end =
  222. start + chunkSize >= file.size ? file.size : start + chunkSize;
  223. fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
  224. }
  225. },
  226. async computeMD5Success(md5edFile) {
  227. const file = await this.getSuccessChunks(md5edFile);
  228. try {
  229. if (file.uploadID == '' || file.uuid == '') {
  230. // 未上传过
  231. await this.newMultiUpload(file);
  232. if (file.uploadID != '' && file.uuid != '') {
  233. file.chunks = '';
  234. this.multipartUpload(file);
  235. } else {
  236. // 失败如何处理
  237. return;
  238. }
  239. return;
  240. }
  241. if (file.uploaded == '1') {
  242. // 已上传成功
  243. // 秒传
  244. if (file.attachID == '0') {
  245. // 删除数据集记录,未删除文件
  246. await addAttachment(file);
  247. }
  248. //不同数据集上传同一个文件
  249. if (file.datasetID != '') {
  250. if (file.datasetName != "" && file.realName != "") {
  251. var info = "该文件已上传,对应数据集(" + file.datasetName + ")-文件(" + file.realName + ")";
  252. window.alert(info);
  253. window.location.reload();
  254. }
  255. }
  256. console.log('文件已上传完成');
  257. this.progress = 100;
  258. this.status = this.dropzoneParams.data('upload-complete');
  259. this.finishUpload(file);
  260. } else {
  261. // 断点续传
  262. this.multipartUpload(file);
  263. }
  264. } catch (error) {
  265. this.emitDropzoneFailed(file);
  266. console.log(error);
  267. }
  268. async function addAttachment(file) {
  269. return await axios.post(
  270. '/attachments/add',
  271. qs.stringify({
  272. uuid: file.uuid,
  273. file_name: file.name,
  274. size: file.size,
  275. dataset_id: file.datasetId,
  276. type: this.uploadtype,
  277. _csrf: csrf
  278. })
  279. );
  280. }
  281. },
  282. async getSuccessChunks(file) {
  283. const params = {
  284. params: {
  285. md5: file.uniqueIdentifier,
  286. type: this.uploadtype,
  287. file_name: file.name,
  288. _csrf: csrf
  289. }
  290. };
  291. try {
  292. const response = await axios.get('/attachments/get_chunks', params);
  293. file.uploadID = response.data.uploadID;
  294. file.uuid = response.data.uuid;
  295. file.uploaded = response.data.uploaded;
  296. file.chunks = response.data.chunks;
  297. file.attachID = response.data.attachID;
  298. file.datasetID = response.data.datasetID;
  299. file.datasetName = response.data.datasetName;
  300. file.realName = response.data.fileName;
  301. return file;
  302. } catch (error) {
  303. this.emitDropzoneFailed(file);
  304. console.log('getSuccessChunks catch: ', error);
  305. return null;
  306. }
  307. },
  308. async newMultiUpload(file) {
  309. const res = await axios.get('/attachments/new_multipart', {
  310. params: {
  311. totalChunkCounts: file.totalChunkCounts,
  312. md5: file.uniqueIdentifier,
  313. size: file.size,
  314. fileType: file.type,
  315. type: this.uploadtype,
  316. file_name: file.name,
  317. _csrf: csrf
  318. }
  319. });
  320. file.uploadID = res.data.uploadID;
  321. file.uuid = res.data.uuid;
  322. },
  323. multipartUpload(file) {
  324. const blobSlice =
  325. File.prototype.slice ||
  326. File.prototype.mozSlice ||
  327. File.prototype.webkitSlice,
  328. //chunkSize = 1024 * 1024 * 32,
  329. chunks = Math.ceil(file.size / chunkSize),
  330. fileReader = new FileReader(),
  331. time = new Date().getTime();
  332. let currentChunk = 0;
  333. let _this = this
  334. function loadNext() {
  335. const start = currentChunk * chunkSize;
  336. const end =
  337. start + chunkSize >= file.size ? file.size : start + chunkSize;
  338. fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
  339. }
  340. function checkSuccessChunks() {
  341. const index = successChunks.indexOf((currentChunk + 1).toString());
  342. if (index == -1) {
  343. return false;
  344. }
  345. return true;
  346. }
  347. async function getUploadChunkUrl(currentChunk, partSize) {
  348. const res = await axios.get('/attachments/get_multipart_url', {
  349. params: {
  350. uuid: file.uuid,
  351. uploadID: file.uploadID,
  352. size: partSize,
  353. chunkNumber: currentChunk + 1,
  354. type: _this.uploadtype,
  355. file_name: file.name,
  356. _csrf: csrf
  357. }
  358. });
  359. urls[currentChunk] = res.data.url;
  360. }
  361. async function uploadMinio(url, e) {
  362. const res = await axios.put(url, e.target.result);
  363. delete e.target.result
  364. etags[currentChunk] = res.headers.etag;
  365. }
  366. async function uploadMinioNewMethod(url,e){
  367. var xhr = new XMLHttpRequest();
  368. xhr.open('PUT', url, false);
  369. if(_this.uploadtype===0){
  370. xhr.setRequestHeader('Content-Type', 'text/plain')
  371. xhr.send(e.target.result);
  372. var etagValue = xhr.getResponseHeader('etag');
  373. etags[currentChunk] = etagValue;
  374. }
  375. else if(_this.uploadtype===1){
  376. xhr.setRequestHeader('Content-Type', '')
  377. xhr.send(e.target.result);
  378. var etagValue = xhr.getResponseHeader('ETag');
  379. //console.log(etagValue);
  380. etags[currentChunk] = etagValue;
  381. }
  382. }
  383. async function updateChunk(currentChunk) {
  384. await axios.post(
  385. '/attachments/update_chunk',
  386. qs.stringify({
  387. uuid: file.uuid,
  388. chunkNumber: currentChunk + 1,
  389. etag: etags[currentChunk],
  390. _csrf: csrf
  391. })
  392. );
  393. }
  394. async function uploadChunk(e) {
  395. try {
  396. if (!checkSuccessChunks()) {
  397. const start = currentChunk * chunkSize;
  398. const partSize =
  399. start + chunkSize >= file.size ? file.size - start : chunkSize;
  400. // 获取分片上传url
  401. await getUploadChunkUrl(currentChunk, partSize);
  402. if (urls[currentChunk] != '') {
  403. // 上传到minio
  404. //await uploadMinio(urls[currentChunk], e);
  405. await uploadMinioNewMethod(urls[currentChunk], e);
  406. if (etags[currentChunk] != '') {
  407. // 更新数据库:分片上传结果
  408. //await updateChunk(currentChunk);
  409. } else {
  410. console.log("上传到minio uploadChunk etags[currentChunk] == ''");// TODO
  411. }
  412. } else {
  413. console.log("uploadChunk urls[currentChunk] != ''");// TODO
  414. }
  415. }
  416. } catch (error) {
  417. console.log(error);
  418. //this.emitDropzoneFailed(file);
  419. //console.log(error);
  420. }
  421. }
  422. async function completeUpload() {
  423. return await axios.post(
  424. '/attachments/complete_multipart',
  425. qs.stringify({
  426. uuid: file.uuid,
  427. uploadID: file.uploadID,
  428. file_name: file.name,
  429. size: file.size,
  430. dataset_id: file.datasetId,
  431. type: _this.uploadtype,
  432. _csrf: csrf,
  433. description:_this.desc
  434. })
  435. );
  436. }
  437. const successChunks = [];
  438. let successParts = [];
  439. successParts = file.chunks.split(',');
  440. for (let i = 0; i < successParts.length; i++) {
  441. successChunks[i] = successParts[i].split('-')[0];
  442. }
  443. const urls = []; // TODO const ?
  444. const etags = [];
  445. console.log('上传分片...');
  446. this.status = this.dropzoneParams.data('uploading');
  447. loadNext();
  448. fileReader.onload = async (e) => {
  449. await uploadChunk(e);
  450. fileReader.abort();
  451. currentChunk++;
  452. if (currentChunk < chunks) {
  453. console.log(
  454. `第${currentChunk}个分片上传完成, 开始第${currentChunk +
  455. 1}/${chunks}个分片上传`
  456. );
  457. this.progress = Math.ceil((currentChunk / chunks) * 100);
  458. this.updateProgress(file, ((currentChunk / chunks) * 100).toFixed(2));
  459. this.status = `${this.dropzoneParams.data('uploading')} ${(
  460. (currentChunk / chunks) *
  461. 100
  462. ).toFixed(2)}%`;
  463. await loadNext();
  464. } else {
  465. await completeUpload();
  466. console.log(
  467. `文件上传完成:${file.name} \n分片:${chunks} 大小:${
  468. file.size
  469. } 用时:${(new Date().getTime() - time) / 1000} s`
  470. );
  471. this.updateProgress(file, 100);
  472. this.progress = 100;
  473. this.status = this.dropzoneParams.data('upload-complete');
  474. this.finishUpload(file);
  475. }
  476. };
  477. }
  478. }
  479. };
  480. </script>
  481. <style>
  482. .dropzone-wrapper {
  483. margin: 0;
  484. }
  485. .ui .dropzone {
  486. border: 2px dashed #0087f5;
  487. box-shadow: none !important;
  488. padding: 0;
  489. min-height: 5rem;
  490. border-radius: 4px;
  491. }
  492. .dataset .dataset-files #dataset .dz-preview.dz-file-preview,
  493. .dataset .dataset-files #dataset .dz-preview.dz-processing {
  494. display: flex;
  495. align-items: center;
  496. }
  497. .dataset .dataset-files #dataset .dz-preview {
  498. border-bottom: 1px solid #dadce0;
  499. min-height: 0;
  500. }
  501. .upload-info{
  502. margin-top: 1em;
  503. margin-bottom: 3em;
  504. }
  505. </style>