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

5 years ago
5 years ago
5 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
5 years ago
5 years ago
5 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
4 years ago
3 years ago
5 years ago
5 years ago
5 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. _csrf: csrf
  275. }
  276. };
  277. try {
  278. const response = await axios.get('/attachments/get_chunks', params);
  279. file.uploadID = response.data.uploadID;
  280. file.uuid = response.data.uuid;
  281. file.uploaded = response.data.uploaded;
  282. file.chunks = response.data.chunks;
  283. file.attachID = response.data.attachID;
  284. file.datasetID = response.data.datasetID;
  285. file.datasetName = response.data.datasetName;
  286. file.realName = response.data.fileName;
  287. return file;
  288. } catch (error) {
  289. this.emitDropzoneFailed(file);
  290. console.log('getSuccessChunks catch: ', error);
  291. return null;
  292. }
  293. },
  294. async newMultiUpload(file) {
  295. console.log(this.uploadtype,this)
  296. const res = await axios.get('/attachments/new_multipart', {
  297. params: {
  298. totalChunkCounts: file.totalChunkCounts,
  299. md5: file.uniqueIdentifier,
  300. size: file.size,
  301. fileType: file.type,
  302. type: this.uploadtype,
  303. _csrf: csrf
  304. }
  305. });
  306. file.uploadID = res.data.uploadID;
  307. file.uuid = res.data.uuid;
  308. },
  309. multipartUpload(file) {
  310. const blobSlice =
  311. File.prototype.slice ||
  312. File.prototype.mozSlice ||
  313. File.prototype.webkitSlice,
  314. chunkSize = 1024 * 1024 * 32,
  315. chunks = Math.ceil(file.size / chunkSize),
  316. fileReader = new FileReader(),
  317. time = new Date().getTime();
  318. let currentChunk = 0;
  319. let _this = this
  320. function loadNext() {
  321. const start = currentChunk * chunkSize;
  322. const end =
  323. start + chunkSize >= file.size ? file.size : start + chunkSize;
  324. fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
  325. }
  326. function checkSuccessChunks() {
  327. const index = successChunks.indexOf((currentChunk + 1).toString());
  328. if (index == -1) {
  329. return false;
  330. }
  331. return true;
  332. }
  333. async function getUploadChunkUrl(currentChunk, partSize) {
  334. const res = await axios.get('/attachments/get_multipart_url', {
  335. params: {
  336. uuid: file.uuid,
  337. uploadID: file.uploadID,
  338. size: partSize,
  339. chunkNumber: currentChunk + 1,
  340. type: _this.uploadtype,
  341. _csrf: csrf
  342. }
  343. });
  344. urls[currentChunk] = res.data.url;
  345. }
  346. async function uploadMinio(url, e) {
  347. const res = await axios.put(url, e.target.result);
  348. delete e.target.result
  349. etags[currentChunk] = res.headers.etag;
  350. }
  351. async function uploadMinioNewMethod(url,e){
  352. var xhr = new XMLHttpRequest();
  353. xhr.open('PUT', url, false);
  354. if(_this.uploadtype===0){
  355. xhr.setRequestHeader('Content-Type', 'text/plain')
  356. xhr.send(e.target.result);
  357. var etagValue = xhr.getResponseHeader('etag');
  358. etags[currentChunk] = etagValue;
  359. }
  360. else if(_this.uploadtype===1){
  361. xhr.setRequestHeader('Content-Type', '')
  362. xhr.send(e.target.result);
  363. var etagValue = xhr.getResponseHeader('ETag');
  364. //console.log(etagValue);
  365. etags[currentChunk] = etagValue;
  366. }
  367. }
  368. async function updateChunk(currentChunk) {
  369. await axios.post(
  370. '/attachments/update_chunk',
  371. qs.stringify({
  372. uuid: file.uuid,
  373. chunkNumber: currentChunk + 1,
  374. etag: etags[currentChunk],
  375. _csrf: csrf
  376. })
  377. );
  378. }
  379. async function uploadChunk(e) {
  380. try {
  381. if (!checkSuccessChunks()) {
  382. const start = currentChunk * chunkSize;
  383. const partSize =
  384. start + chunkSize >= file.size ? file.size - start : chunkSize;
  385. // 获取分片上传url
  386. await getUploadChunkUrl(currentChunk, partSize);
  387. if (urls[currentChunk] != '') {
  388. // 上传到minio
  389. //await uploadMinio(urls[currentChunk], e);
  390. await uploadMinioNewMethod(urls[currentChunk], e);
  391. if (etags[currentChunk] != '') {
  392. // 更新数据库:分片上传结果
  393. //await updateChunk(currentChunk);
  394. } else {
  395. console.log("上传到minio uploadChunk etags[currentChunk] == ''");// TODO
  396. }
  397. } else {
  398. console.log("uploadChunk urls[currentChunk] != ''");// TODO
  399. }
  400. }
  401. } catch (error) {
  402. console.log(error);
  403. //this.emitDropzoneFailed(file);
  404. //console.log(error);
  405. }
  406. }
  407. async function completeUpload() {
  408. console.log(_this.uploadtype)
  409. return await axios.post(
  410. '/attachments/complete_multipart',
  411. qs.stringify({
  412. uuid: file.uuid,
  413. uploadID: file.uploadID,
  414. file_name: file.name,
  415. size: file.size,
  416. dataset_id: file.datasetId,
  417. type: _this.uploadtype,
  418. _csrf: csrf,
  419. description:_this.desc
  420. })
  421. );
  422. }
  423. const successChunks = [];
  424. let successParts = [];
  425. successParts = file.chunks.split(',');
  426. for (let i = 0; i < successParts.length; i++) {
  427. successChunks[i] = successParts[i].split('-')[0];
  428. }
  429. const urls = []; // TODO const ?
  430. const etags = [];
  431. console.log('上传分片...');
  432. this.status = this.dropzoneParams.data('uploading');
  433. loadNext();
  434. fileReader.onload = async (e) => {
  435. await uploadChunk(e);
  436. fileReader.abort();
  437. currentChunk++;
  438. if (currentChunk < chunks) {
  439. console.log(
  440. `第${currentChunk}个分片上传完成, 开始第${currentChunk +
  441. 1}/${chunks}个分片上传`
  442. );
  443. this.progress = Math.ceil((currentChunk / chunks) * 100);
  444. this.updateProgress(file, ((currentChunk / chunks) * 100).toFixed(2));
  445. this.status = `${this.dropzoneParams.data('uploading')} ${(
  446. (currentChunk / chunks) *
  447. 100
  448. ).toFixed(2)}%`;
  449. await loadNext();
  450. } else {
  451. await completeUpload();
  452. console.log(
  453. `文件上传完成:${file.name} \n分片:${chunks} 大小:${
  454. file.size
  455. } 用时:${(new Date().getTime() - time) / 1000} s`
  456. );
  457. this.progress = 100;
  458. this.status = this.dropzoneParams.data('upload-complete');
  459. this.finishUpload(file);
  460. }
  461. };
  462. }
  463. }
  464. };
  465. </script>
  466. <style>
  467. .dropzone-wrapper {
  468. margin: 0;
  469. }
  470. .ui .dropzone {
  471. border: 2px dashed #0087f5;
  472. box-shadow: none !important;
  473. padding: 0;
  474. min-height: 5rem;
  475. border-radius: 4px;
  476. }
  477. .dataset .dataset-files #dataset .dz-preview.dz-file-preview,
  478. .dataset .dataset-files #dataset .dz-preview.dz-processing {
  479. display: flex;
  480. align-items: center;
  481. }
  482. .dataset .dataset-files #dataset .dz-preview {
  483. border-bottom: 1px solid #dadce0;
  484. min-height: 0;
  485. }
  486. .upload-info{
  487. margin-top: 1em;
  488. margin-bottom: 3em;
  489. }
  490. </style>