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

4 years ago
4 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
4 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
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 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
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 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
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. chunks = Math.ceil(file.size / chunkSize),
  182. spark = new SparkMD5.ArrayBuffer(),
  183. fileReader = new FileReader();
  184. let currentChunk = 0;
  185. const time = new Date().getTime();
  186. // console.log('计算MD5...')
  187. this.status = this.dropzoneParams.data('md5-computing');
  188. file.totalChunkCounts = chunks;
  189. loadNext();
  190. fileReader.onload = (e) => {
  191. fileLoaded.call(this, e);
  192. };
  193. fileReader.onerror = (err) => {
  194. console.warn('oops, something went wrong.', err);
  195. file.cancel();
  196. };
  197. function fileLoaded(e) {
  198. spark.append(e.target.result); // Append array buffer
  199. currentChunk++;
  200. if (currentChunk < chunks) {
  201. // console.log(`第${currentChunk}分片解析完成, 开始第${currentChunk +1}/${chunks}分片解析`);
  202. this.status = `${this.dropzoneParams.data('loading-file')} ${(
  203. (currentChunk / chunks) *
  204. 100
  205. ).toFixed(2)}% (${currentChunk}/${chunks})`;
  206. this.updateProgress(file, ((currentChunk / chunks) * 100).toFixed(2));
  207. loadNext();
  208. return;
  209. }
  210. const md5 = spark.end();
  211. console.log(
  212. `MD5计算完成:${file.name} \nMD5:${md5} \n分片:${chunks} 大小:${
  213. file.size
  214. } 用时:${(new Date().getTime() - time) / 1000} s`
  215. );
  216. spark.destroy(); // 释放缓存
  217. file.uniqueIdentifier = md5; // 将文件md5赋值给文件唯一标识
  218. file.cmd5 = false; // 取消计算md5状态
  219. this.computeMD5Success(file);
  220. }
  221. function loadNext() {
  222. const start = currentChunk * chunkSize;
  223. const end =
  224. start + chunkSize >= file.size ? file.size : start + chunkSize;
  225. fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
  226. }
  227. },
  228. async computeMD5Success(md5edFile) {
  229. const file = await this.getSuccessChunks(md5edFile);
  230. try {
  231. if (file.uploadID == '' || file.uuid == '') {
  232. // 未上传过
  233. await this.newMultiUpload(file);
  234. if (file.uploadID != '' && file.uuid != '') {
  235. file.chunks = '';
  236. this.multipartUpload(file);
  237. } else {
  238. // 失败如何处理
  239. return;
  240. }
  241. return;
  242. }
  243. if (file.uploaded == '1') {
  244. // 已上传成功
  245. // 秒传
  246. if (file.attachID == '0') {
  247. // 删除数据集记录,未删除文件
  248. await addAttachment(file);
  249. }
  250. //不同数据集上传同一个文件
  251. if (file.datasetID != '') {
  252. if (file.datasetName != "" && file.realName != "") {
  253. var info = "该文件已上传,对应数据集(" + file.datasetName + ")-文件(" + file.realName + ")";
  254. window.alert(info);
  255. window.location.reload();
  256. }
  257. }
  258. console.log('文件已上传完成');
  259. this.progress = 100;
  260. this.status = this.dropzoneParams.data('upload-complete');
  261. this.finishUpload(file);
  262. } else {
  263. // 断点续传
  264. this.multipartUpload(file);
  265. }
  266. } catch (error) {
  267. this.emitDropzoneFailed(file);
  268. console.log(error);
  269. }
  270. async function addAttachment(file) {
  271. return await axios.post(
  272. '/attachments/add',
  273. qs.stringify({
  274. uuid: file.uuid,
  275. file_name: file.name,
  276. size: file.size,
  277. dataset_id: file.datasetId,
  278. type: this.uploadtype,
  279. _csrf: csrf
  280. })
  281. );
  282. }
  283. },
  284. async getSuccessChunks(file) {
  285. const params = {
  286. params: {
  287. md5: file.uniqueIdentifier,
  288. type: this.uploadtype,
  289. file_name: file.name,
  290. _csrf: csrf
  291. }
  292. };
  293. try {
  294. const response = await axios.get('/attachments/get_chunks', params);
  295. file.uploadID = response.data.uploadID;
  296. file.uuid = response.data.uuid;
  297. file.uploaded = response.data.uploaded;
  298. file.chunks = response.data.chunks;
  299. file.attachID = response.data.attachID;
  300. file.datasetID = response.data.datasetID;
  301. file.datasetName = response.data.datasetName;
  302. file.realName = response.data.fileName;
  303. return file;
  304. } catch (error) {
  305. this.emitDropzoneFailed(file);
  306. console.log('getSuccessChunks catch: ', error);
  307. return null;
  308. }
  309. },
  310. async newMultiUpload(file) {
  311. console.log(this.uploadtype,this)
  312. const res = await axios.get('/attachments/new_multipart', {
  313. params: {
  314. totalChunkCounts: file.totalChunkCounts,
  315. md5: file.uniqueIdentifier,
  316. size: file.size,
  317. fileType: file.type,
  318. type: this.uploadtype,
  319. file_name: file.name,
  320. _csrf: csrf
  321. }
  322. });
  323. file.uploadID = res.data.uploadID;
  324. file.uuid = res.data.uuid;
  325. },
  326. multipartUpload(file) {
  327. const blobSlice =
  328. File.prototype.slice ||
  329. File.prototype.mozSlice ||
  330. File.prototype.webkitSlice,
  331. chunkSize = 1024 * 1024 * 32,
  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. console.log(_this.uploadtype)
  427. return await axios.post(
  428. '/attachments/complete_multipart',
  429. qs.stringify({
  430. uuid: file.uuid,
  431. uploadID: file.uploadID,
  432. file_name: file.name,
  433. size: file.size,
  434. dataset_id: file.datasetId,
  435. type: _this.uploadtype,
  436. _csrf: csrf,
  437. description:_this.desc
  438. })
  439. );
  440. }
  441. const successChunks = [];
  442. let successParts = [];
  443. successParts = file.chunks.split(',');
  444. for (let i = 0; i < successParts.length; i++) {
  445. successChunks[i] = successParts[i].split('-')[0];
  446. }
  447. const urls = []; // TODO const ?
  448. const etags = [];
  449. console.log('上传分片...');
  450. this.status = this.dropzoneParams.data('uploading');
  451. loadNext();
  452. fileReader.onload = async (e) => {
  453. await uploadChunk(e);
  454. fileReader.abort();
  455. currentChunk++;
  456. if (currentChunk < chunks) {
  457. console.log(
  458. `第${currentChunk}个分片上传完成, 开始第${currentChunk +
  459. 1}/${chunks}个分片上传`
  460. );
  461. this.progress = Math.ceil((currentChunk / chunks) * 100);
  462. console.log("((currentChunk / chunks) * 100).toFixed(2)",((currentChunk / chunks) * 100).toFixed(2))
  463. this.updateProgress(file, ((currentChunk / chunks) * 100).toFixed(2));
  464. this.status = `${this.dropzoneParams.data('uploading')} ${(
  465. (currentChunk / chunks) *
  466. 100
  467. ).toFixed(2)}%`;
  468. await loadNext();
  469. } else {
  470. await completeUpload();
  471. console.log(
  472. `文件上传完成:${file.name} \n分片:${chunks} 大小:${
  473. file.size
  474. } 用时:${(new Date().getTime() - time) / 1000} s`
  475. );
  476. this.updateProgress(file, 100);
  477. this.progress = 100;
  478. this.status = this.dropzoneParams.data('upload-complete');
  479. this.finishUpload(file);
  480. }
  481. };
  482. }
  483. }
  484. };
  485. </script>
  486. <style>
  487. .dropzone-wrapper {
  488. margin: 0;
  489. }
  490. .ui .dropzone {
  491. border: 2px dashed #0087f5;
  492. box-shadow: none !important;
  493. padding: 0;
  494. min-height: 5rem;
  495. border-radius: 4px;
  496. }
  497. .dataset .dataset-files #dataset .dz-preview.dz-file-preview,
  498. .dataset .dataset-files #dataset .dz-preview.dz-processing {
  499. display: flex;
  500. align-items: center;
  501. }
  502. .dataset .dataset-files #dataset .dz-preview {
  503. border-bottom: 1px solid #dadce0;
  504. min-height: 0;
  505. }
  506. .upload-info{
  507. margin-top: 1em;
  508. margin-bottom: 3em;
  509. }
  510. </style>