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