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 14 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. <span class="success">{{ status }}</span>
  10. </p>
  11. </div>
  12. </template>
  13. <script>
  14. /* eslint-disable eqeqeq */
  15. // import Dropzone from 'dropzone/dist/dropzone.js';
  16. // import 'dropzone/dist/dropzone.css'
  17. import SparkMD5 from 'spark-md5';
  18. import axios from 'axios';
  19. import qs from 'qs';
  20. import createDropzone from '../features/dropzone.js';
  21. const {_AppSubUrl, _StaticUrlPrefix, csrf} = window.config;
  22. export default {
  23. data() {
  24. return {
  25. dropzoneUploader: null,
  26. maxFiles: 1,
  27. maxFilesize: 1 * 1024 * 1024 * 1024 * 1024,
  28. acceptedFiles: '*/*',
  29. progress: 0,
  30. status: '',
  31. dropzoneParams: {},
  32. file_status_text: ''
  33. };
  34. },
  35. async mounted() {
  36. this.dropzoneParams = $('div#minioUploader-params');
  37. this.file_status_text = this.dropzoneParams.data('file-status');
  38. this.status = this.dropzoneParams.data('file-init-status');
  39. let previewTemplate = '';
  40. previewTemplate += '<div class="dz-preview dz-file-preview">\n ';
  41. previewTemplate += ' <div class="dz-details">\n ';
  42. previewTemplate += ' <div class="dz-filename">';
  43. previewTemplate +=
  44. ' <span data-dz-name data-dz-thumbnail></span>';
  45. previewTemplate += ' </div>\n ';
  46. previewTemplate += ' <div class="dz-size" data-dz-size></div>\n ';
  47. previewTemplate += ' </div>\n ';
  48. previewTemplate += ' <div class="dz-progress ui active progress">';
  49. previewTemplate +=
  50. ' <div class="dz-upload bar" data-dz-uploadprogress><div class="progress"></div></div>\n ';
  51. previewTemplate += ' </div>\n ';
  52. previewTemplate += ' <div class="dz-success-mark">';
  53. previewTemplate += ' <span>上传成功</span>';
  54. previewTemplate += ' </div>\n ';
  55. previewTemplate += ' <div class="dz-error-mark">';
  56. previewTemplate += ' <span>上传失败</span>';
  57. previewTemplate += ' </div>\n ';
  58. previewTemplate += ' <div class="dz-error-message">';
  59. previewTemplate += ' <span data-dz-errormessage></span>';
  60. previewTemplate += ' </div>\n';
  61. previewTemplate += '</div>';
  62. const $dropzone = $('div#dataset');
  63. console.log('createDropzone');
  64. const dropzoneUploader = await createDropzone($dropzone[0], {
  65. url: '/todouploader',
  66. maxFiles: this.maxFiles,
  67. maxFilesize: this.maxFileSize,
  68. timeout: 0,
  69. autoQueue: false,
  70. dictDefaultMessage: this.dropzoneParams.data('default-message'),
  71. dictInvalidFileType: this.dropzoneParams.data('invalid-input-type'),
  72. dictFileTooBig: this.dropzoneParams.data('file-too-big'),
  73. dictRemoveFile: this.dropzoneParams.data('remove-file'),
  74. previewTemplate
  75. });
  76. dropzoneUploader.on('addedfile', (file) => {
  77. setTimeout(() => {
  78. // eslint-disable-next-line no-unused-expressions
  79. file.accepted && this.onFileAdded(file);
  80. }, 200);
  81. });
  82. dropzoneUploader.on('maxfilesexceeded', function (file) {
  83. if (this.files[0].status !== 'success') {
  84. alert(this.dropzoneParams.data('waitting-uploading'));
  85. this.removeFile(file);
  86. return;
  87. }
  88. this.removeAllFiles();
  89. this.addFile(file);
  90. });
  91. this.dropzoneUploader = dropzoneUploader;
  92. },
  93. methods: {
  94. resetStatus() {
  95. this.progress = 0;
  96. this.status = '';
  97. },
  98. updateProgress(file, progress) {
  99. file.previewTemplate.querySelector(
  100. '.dz-upload'
  101. ).style.width = `${progress}%`;
  102. },
  103. emitDropzoneSuccess(file) {
  104. file.status = 'success';
  105. this.dropzoneUploader.emit('success', file);
  106. this.dropzoneUploader.emit('complete', file);
  107. },
  108. emitDropzoneFailed(file) {
  109. this.status = this.dropzoneParams.data('falied');
  110. file.status = 'error';
  111. this.dropzoneUploader.emit('error', file);
  112. // this.dropzoneUploader.emit('complete', file);
  113. },
  114. onFileAdded(file) {
  115. file.datasetId = document
  116. .getElementById('datasetId')
  117. .getAttribute('datasetId');
  118. this.resetStatus();
  119. this.computeMD5(file);
  120. },
  121. finishUpload(file) {
  122. this.emitDropzoneSuccess(file);
  123. setTimeout(() => {
  124. window.location.reload();
  125. }, 1000);
  126. },
  127. computeMD5(file) {
  128. this.resetStatus();
  129. const blobSlice =
  130. File.prototype.slice ||
  131. File.prototype.mozSlice ||
  132. File.prototype.webkitSlice,
  133. chunkSize = 1024 * 1024 * 64,
  134. chunks = Math.ceil(file.size / chunkSize),
  135. spark = new SparkMD5.ArrayBuffer(),
  136. fileReader = new FileReader();
  137. let currentChunk = 0;
  138. const time = new Date().getTime();
  139. // console.log('计算MD5...')
  140. this.status = this.dropzoneParams.data('md5-computing');
  141. file.totalChunkCounts = chunks;
  142. loadNext();
  143. fileReader.onload = (e) => {
  144. fileLoaded.call(this, e);
  145. };
  146. fileReader.onerror = (err) => {
  147. console.warn('oops, something went wrong.', err);
  148. file.cancel();
  149. };
  150. function fileLoaded(e) {
  151. spark.append(e.target.result); // Append array buffer
  152. currentChunk++;
  153. if (currentChunk < chunks) {
  154. // console.log(`第${currentChunk}分片解析完成, 开始第${currentChunk +1}/${chunks}分片解析`);
  155. this.status = `${this.dropzoneParams.data('loading-file')} ${(
  156. (currentChunk / chunks) *
  157. 100
  158. ).toFixed(2)}% (${currentChunk}/${chunks})`;
  159. this.updateProgress(file, ((currentChunk / chunks) * 100).toFixed(2));
  160. loadNext();
  161. return;
  162. }
  163. const md5 = spark.end();
  164. console.log(
  165. `MD5计算完成:${file.name} \nMD5:${md5} \n分片:${chunks} 大小:${
  166. file.size
  167. } 用时:${(new Date().getTime() - time) / 1000} s`
  168. );
  169. spark.destroy(); // 释放缓存
  170. file.uniqueIdentifier = md5; // 将文件md5赋值给文件唯一标识
  171. file.cmd5 = false; // 取消计算md5状态
  172. this.computeMD5Success(file);
  173. }
  174. function loadNext() {
  175. const start = currentChunk * chunkSize;
  176. const end =
  177. start + chunkSize >= file.size ? file.size : start + chunkSize;
  178. fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
  179. }
  180. },
  181. async computeMD5Success(md5edFile) {
  182. const file = await this.getSuccessChunks(md5edFile);
  183. try {
  184. if (file.uploadID == '' || file.uuid == '') {
  185. // 未上传过
  186. await this.newMultiUpload(file);
  187. if (file.uploadID != '' && file.uuid != '') {
  188. file.chunks = '';
  189. this.multipartUpload(file);
  190. } else {
  191. // 失败如何处理
  192. return;
  193. }
  194. return;
  195. }
  196. if (file.uploaded == '1') {
  197. // 已上传成功
  198. // 秒传
  199. if (file.attachID == '0') {
  200. // 删除数据集记录,未删除文件
  201. await addAttachment(file);
  202. }
  203. console.log('文件已上传完成');
  204. this.progress = 100;
  205. this.status = this.dropzoneParams.data('upload-complete');
  206. this.finishUpload(file);
  207. } else {
  208. // 断点续传
  209. this.multipartUpload(file);
  210. }
  211. } catch (error) {
  212. this.emitDropzoneFailed(file);
  213. console.log(error);
  214. }
  215. async function addAttachment(file) {
  216. return await axios.post(
  217. '/attachments/add',
  218. qs.stringify({
  219. uuid: file.uuid,
  220. file_name: file.name,
  221. size: file.size,
  222. dataset_id: file.datasetId,
  223. _csrf: csrf
  224. })
  225. );
  226. }
  227. },
  228. async getSuccessChunks(file) {
  229. const params = {
  230. params: {
  231. md5: file.uniqueIdentifier,
  232. _csrf: csrf
  233. }
  234. };
  235. try {
  236. const response = await axios.get('/attachments/get_chunks', params);
  237. file.uploadID = response.data.uploadID;
  238. file.uuid = response.data.uuid;
  239. file.uploaded = response.data.uploaded;
  240. file.chunks = response.data.chunks;
  241. file.attachID = response.data.attachID;
  242. return file;
  243. } catch (error) {
  244. this.emitDropzoneFailed(file);
  245. console.log('getSuccessChunks catch: ', error);
  246. return null;
  247. }
  248. },
  249. async newMultiUpload(file) {
  250. const res = await axios.get('/attachments/new_multipart', {
  251. params: {
  252. totalChunkCounts: file.totalChunkCounts,
  253. md5: file.uniqueIdentifier,
  254. size: file.size,
  255. fileType: file.type,
  256. _csrf: csrf
  257. }
  258. });
  259. file.uploadID = res.data.uploadID;
  260. file.uuid = res.data.uuid;
  261. },
  262. multipartUpload(file) {
  263. const blobSlice =
  264. File.prototype.slice ||
  265. File.prototype.mozSlice ||
  266. File.prototype.webkitSlice,
  267. chunkSize = 1024 * 1024 * 64,
  268. chunks = Math.ceil(file.size / chunkSize),
  269. fileReader = new FileReader(),
  270. time = new Date().getTime();
  271. let currentChunk = 0;
  272. function loadNext() {
  273. const start = currentChunk * chunkSize;
  274. const end =
  275. start + chunkSize >= file.size ? file.size : start + chunkSize;
  276. fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
  277. }
  278. function checkSuccessChunks() {
  279. const index = successChunks.indexOf((currentChunk + 1).toString());
  280. if (index == -1) {
  281. return false;
  282. }
  283. return true;
  284. }
  285. async function getUploadChunkUrl(currentChunk, partSize) {
  286. const res = await axios.get('/attachments/get_multipart_url', {
  287. params: {
  288. uuid: file.uuid,
  289. uploadID: file.uploadID,
  290. size: partSize,
  291. chunkNumber: currentChunk + 1,
  292. _csrf: csrf
  293. }
  294. });
  295. urls[currentChunk] = res.data.url;
  296. }
  297. async function uploadMinio(url, e) {
  298. const res = await axios.put(url, e.target.result);
  299. etags[currentChunk] = res.headers.etag;
  300. }
  301. async function updateChunk(currentChunk) {
  302. await axios.post(
  303. '/attachments/update_chunk',
  304. qs.stringify({
  305. uuid: file.uuid,
  306. chunkNumber: currentChunk + 1,
  307. etag: etags[currentChunk],
  308. _csrf: csrf
  309. })
  310. );
  311. }
  312. async function uploadChunk(e) {
  313. try {
  314. if (!checkSuccessChunks()) {
  315. const start = currentChunk * chunkSize;
  316. const partSize =
  317. start + chunkSize >= file.size ? file.size - start : chunkSize;
  318. // 获取分片上传url
  319. await getUploadChunkUrl(currentChunk, partSize);
  320. if (urls[currentChunk] != '') {
  321. // 上传到minio
  322. await uploadMinio(urls[currentChunk], e);
  323. if (etags[currentChunk] != '') {
  324. // 更新数据库:分片上传结果
  325. await updateChunk(currentChunk);
  326. } else {
  327. console.log("上传到minio uploadChunk etags[currentChunk] == ''");// TODO
  328. }
  329. } else {
  330. console.log("uploadChunk urls[currentChunk] != ''");// TODO
  331. }
  332. }
  333. } catch (error) {
  334. this.emitDropzoneFailed(file);
  335. console.log(error);
  336. }
  337. }
  338. async function completeUpload() {
  339. return await axios.post(
  340. '/attachments/complete_multipart',
  341. qs.stringify({
  342. uuid: file.uuid,
  343. uploadID: file.uploadID,
  344. file_name: file.name,
  345. size: file.size,
  346. dataset_id: file.datasetId,
  347. _csrf: csrf
  348. })
  349. );
  350. }
  351. const successChunks = [];
  352. let successParts = [];
  353. successParts = file.chunks.split(',');
  354. for (let i = 0; i < successParts.length; i++) {
  355. successChunks[i] = successParts[i].split('-')[0].split('"')[1];
  356. }
  357. const urls = []; // TODO const ?
  358. const etags = [];
  359. console.log('上传分片...');
  360. this.status = this.dropzoneParams.data('uploading');
  361. loadNext();
  362. fileReader.onload = async (e) => {
  363. await uploadChunk(e);
  364. currentChunk++;
  365. if (currentChunk < chunks) {
  366. console.log(
  367. `第${currentChunk}个分片上传完成, 开始第${currentChunk +
  368. 1}/${chunks}个分片上传`
  369. );
  370. this.progress = Math.ceil((currentChunk / chunks) * 100);
  371. this.updateProgress(file, ((currentChunk / chunks) * 100).toFixed(2));
  372. this.status = `${this.dropzoneParams.data('uploading')} ${(
  373. (currentChunk / chunks) *
  374. 100
  375. ).toFixed(2)}%`;
  376. await loadNext();
  377. } else {
  378. await completeUpload();
  379. console.log(
  380. `文件上传完成:${file.name} \n分片:${chunks} 大小:${
  381. file.size
  382. } 用时:${(new Date().getTime() - time) / 1000} s`
  383. );
  384. this.progress = 100;
  385. this.status = this.dropzoneParams.data('upload-complete');
  386. this.finishUpload(file);
  387. }
  388. };
  389. }
  390. }
  391. };
  392. </script>
  393. <style>
  394. .dropzone-wrapper {
  395. margin: 2em auto;
  396. }
  397. .ui .dropzone {
  398. border: 2px dashed #0087f5;
  399. box-shadow: none !important;
  400. padding: 0;
  401. min-height: 5rem;
  402. border-radius: 4px;
  403. }
  404. .dataset .dataset-files #dataset .dz-preview.dz-file-preview,
  405. .dataset .dataset-files #dataset .dz-preview.dz-processing {
  406. display: flex;
  407. align-items: center;
  408. }
  409. .dataset .dataset-files #dataset .dz-preview {
  410. border-bottom: 1px solid #dadce0;
  411. min-height: 0;
  412. }
  413. </style>