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