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