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

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