index.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. <!--
  2. * @Author: zhangyu
  3. * @Date: 2019-11-28 10:05:28
  4. * @Info:
  5. * @LastEditTime : 2019-12-25 17:48:31
  6. -->
  7. <template>
  8. <div id="global-uploader">
  9. <!-- 上传 -->
  10. <uploader
  11. ref="uploader"
  12. :options="options"
  13. :autoStart="false"
  14. @file-added="onFileAdded"
  15. @file-success="onFileSuccess"
  16. @file-progress="onFileProgress"
  17. @file-error="onFileError"
  18. @file-removed="onFileRemoved"
  19. class="uploader-app">
  20. <uploader-unsupport></uploader-unsupport>
  21. <uploader-btn id="global-uploader-btn" :attrs="attrs" ref="uploadBtn">选择文件</uploader-btn>
  22. <uploader-list v-show="panelShow">
  23. <div class="file-panel" slot-scope="props" :class="{'collapse': collapse}">
  24. <div class="file-title">
  25. <h2>文件列表</h2>
  26. <div class="operate">
  27. <el-button @click="fileListShow" style="color:#999;" type="text" :title="collapse ? '折叠':'展开' ">
  28. <i class="iconfont" :class="collapse ? 'icon-bottom': 'icon-top'"></i>
  29. </el-button>
  30. <el-button @click="close" style="color:#999;" type="text" title="关闭">
  31. <i class="iconfont icon-guanbi"></i>
  32. </el-button>
  33. </div>
  34. </div>
  35. <ul class="file-list" v-show="collapse">
  36. <el-scrollbar style="height:100%;">
  37. <li v-for="file in props.fileList" :key="file.id">
  38. <uploader-file :class="'file_' + file.id" ref="files" :file="file" :list="true"></uploader-file>
  39. </li>
  40. <div class="no-file" v-if="!props.fileList.length"><i class="iconfont icon-wushuju"></i> 暂无待上传文件</div>
  41. </el-scrollbar>
  42. </ul>
  43. </div>
  44. </uploader-list>
  45. </uploader>
  46. </div>
  47. </template>
  48. <script>
  49. /**
  50. * 全局上传插件
  51. * 调用方法:Bus.$emit('openUploader', {}) 打开文件选择框,参数为需要传递的额外参数
  52. * 监听函数:Bus.$on('fileAdded', fn); 文件选择后的回调
  53. * Bus.$on('fileSuccess', fn); 文件上传成功的回调
  54. */
  55. import Bus from '@/utils/bus.js';
  56. import SparkMD5 from 'spark-md5';
  57. import { getUploadId, mergeMultipart } from '@/api/uploader';
  58. import request from "@/api/model/file.js";
  59. import { mapGetters, mapMutations } from 'vuex'
  60. export default {
  61. data() {
  62. return {
  63. options: {
  64. target: '/image-service/common/multipart_upload',
  65. chunkSize: 1*1024*1024,
  66. fileParameterName: 'file',
  67. maxChunkRetries: 3,
  68. testChunks: false, //是否开启服务器分片校验
  69. // 服务器分片校验函数,秒传及断点续传基础
  70. // checkChunkUploadedByResponse: function (chunk, message) {
  71. // let objMessage = JSON.parse(message);
  72. // if (objMessage.skipUpload) {
  73. // return true;
  74. // }
  75. // return (objMessage.uploaded || []).indexOf(chunk.offset + 1) >= 0
  76. // },
  77. // headers: {
  78. // Authorization: Ticket.get() && "Bearer " + Ticket.get().access_token
  79. // },
  80. query: this.getFileQuery
  81. },
  82. attrs: {
  83. // accept: ACCEPT_CONFIG.getAll()
  84. },
  85. panelShow: false, //选择文件后,展示上传panel
  86. collapse: false,
  87. }
  88. },
  89. mounted() {
  90. Bus.$on('openUploader', (query, file) => {
  91. if(!this.uploaderList.some(item => {return item.name === file.name})){
  92. if(query.uploadId){
  93. // this.params = query || {};
  94. file.uploadId = query.uploadId
  95. file.modelId = query.modelId? query.modelId: ''
  96. this.uploader.addFile(file)
  97. this.setUploaderList(this.uploader.files.map(item => {
  98. item.modelId = item.file.modelId?item.file.modelId:''
  99. return item
  100. }))
  101. } else {
  102. getUploadId({
  103. systemId: query.systemId?query.systemId:'revit',
  104. secret: query.secret?query.secret:'63afbef6906c342b',
  105. overwrite: query.overwrite? query.overwrite: false,
  106. key: file.name
  107. }, res => {
  108. if(res.UploadId){
  109. // this.params = Object.assign(query, { uploadId: res.UploadId }) || {};
  110. file = Object.assign(file, {
  111. ...query,
  112. uploadId: res.UploadId
  113. })
  114. this.uploader.addFile(file)
  115. this.setUploaderList(this.uploader.files.map(item => {
  116. item.modelId = item.file.modelId?item.file.modelId:'';
  117. return item
  118. }))
  119. } else {
  120. this.$message.error(`请求分片上传接口失败!`);
  121. }
  122. })
  123. }
  124. }else {
  125. this.$message.error(`该文件在上传列表中已存在!`);
  126. }
  127. // if (this.$refs.uploadBtn) {
  128. // document.getElementById('global-uploader-btn').click();
  129. // // $('#global-uploader-btn').click();
  130. // }
  131. });
  132. },
  133. computed: {
  134. ...mapGetters('layout', ['uploaderList']),
  135. //Uploader实例
  136. uploader() {
  137. return this.$refs.uploader.uploader;
  138. }
  139. },
  140. methods: {
  141. ...mapMutations('layout', ['setUploaderList']),
  142. onFileAdded(file) {
  143. this.panelShow = true;
  144. this.collapse = true;
  145. this.computeMD5(file);
  146. Bus.$emit('fileAdded');
  147. },
  148. onFileProgress(rootFile, file, chunk) {
  149. console.log(`上传中 ${file.name},chunk:${chunk.startByte / 1024 / 1024} ~ ${chunk.endByte / 1024 / 1024}`)
  150. },
  151. onFileSuccess(rootFile, file, response, chunk) {
  152. let res = JSON.parse(response);
  153. // 服务器自定义的错误(即虽返回200,但是是错误的情况),这种错误是Uploader无法拦截的
  154. if (!res.Result || res.Result != 'success') {
  155. this.$message({ message: res.ResultMsg?res.ResultMsg:'上传失败!', type: 'error' });
  156. // 文件状态设为“失败”
  157. this.statusSet(file.id, 'failed');
  158. return
  159. }
  160. // 如果服务端返回需要合并
  161. console.log('获取分片数',file.chunks.length)
  162. if (parseInt(res.TotalCount) >= file.chunks.length) {
  163. // 文件状态设为“合并中”
  164. this.statusSet(file.id, 'merging');
  165. if(file.file.modelId){
  166. //模型文件合并专用接口
  167. request.mergeModelFile({ ModelId: file.file.modelId, UploadId: file.file.uploadId }, res => {
  168. Bus.$emit('modelStatusChange')
  169. // 文件合并成功
  170. Bus.$emit('fileSuccess');
  171. this.statusRemove(file.id);
  172. })
  173. } else {
  174. mergeMultipart({
  175. systemId: file.file.systemId?file.file.systemId:'revit',
  176. secret: file.file.secret?file.file.secret:'63afbef6906c342b',
  177. uploadId: file.file.uploadId
  178. }, res => {
  179. // 文件合并成功
  180. Bus.$emit('fileSuccess');
  181. this.statusRemove(file.id);
  182. })
  183. }
  184. // 不需要合并
  185. } else {
  186. Bus.$emit('fileSuccess');
  187. console.log('上传成功');
  188. }
  189. },
  190. onFileError(rootFile, file, response, chunk) {
  191. this.$message({
  192. message: response,
  193. type: 'error'
  194. })
  195. },
  196. onFileRemoved(file) {
  197. this.uploaderList.splice(this.uploaderList.findIndex(item => {
  198. return item.id == file.id;
  199. },1))
  200. this.setUploaderList(this.uploaderList);
  201. if(file.modelId && !file.isComplete()) {
  202. request.deleteModelFileList({Id: file.modelId, Force: true}, res => {
  203. console.log('删除错误模型:',file.modelId);
  204. Bus.$emit('modelStatusChange')
  205. })
  206. }
  207. },
  208. /**
  209. * 计算md5,实现断点续传及秒传
  210. * @param file
  211. */
  212. computeMD5(file) {
  213. let fileReader = new FileReader();
  214. let time = new Date().getTime();
  215. let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
  216. let currentChunk = 0;
  217. const chunkSize = 1 * 1024 * 1024;
  218. let chunks = Math.floor(file.size / chunkSize);
  219. let spark = new SparkMD5.ArrayBuffer();
  220. // 文件状态设为"计算MD5"
  221. this.statusSet(file.id, 'md5');
  222. file.pause();
  223. loadNext();
  224. fileReader.onload = (e => {
  225. spark.append(e.target.result);
  226. if (currentChunk < chunks) {
  227. currentChunk++;
  228. loadNext();
  229. // 实时展示MD5的计算进度
  230. this.$nextTick(() => {
  231. document.getElementsByClassName(`myStatus_${file.id}`)[0].innerText = '校验MD5 '+ ((currentChunk/chunks)*100).toFixed(0)+'%'
  232. // $(`.myStatus_${file.id}`).text('校验MD5 '+ ((currentChunk/chunks)*100).toFixed(0)+'%')
  233. })
  234. } else {
  235. let md5 = spark.end();
  236. file.file.md5 = md5;
  237. this.computeMD5Success(md5, file);
  238. console.log(`MD5计算完毕:${file.name} \nMD5:${md5} \n分片:${chunks} 大小:${file.size} 用时:${new Date().getTime() - time} ms`);
  239. }
  240. });
  241. fileReader.onerror = function () {
  242. this.error(`文件${file.name}读取出错,请检查该文件`)
  243. file.cancel();
  244. };
  245. function loadNext() {
  246. let start = currentChunk * chunkSize;
  247. let end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
  248. fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
  249. }
  250. },
  251. computeMD5Success(md5, file) {
  252. // 将自定义参数直接加载uploader实例的opts上
  253. console.log(this.uploader)
  254. // Object.assign(this.uploader.opts, {
  255. // query: {
  256. // uploadId: file.file.uploadId,
  257. // md5
  258. // }
  259. // })
  260. // file.uniqueIdentifier = this.params.uploadId;
  261. file.resume();
  262. this.statusRemove(file.id);
  263. },
  264. //获取文件参数
  265. getFileQuery(file, chunk) {
  266. return {
  267. uploadId: file.file.uploadId,
  268. md5: file.file.md5
  269. }
  270. },
  271. fileListShow() {
  272. this.collapse = this.collapse? false: true;
  273. // let $list = $('#global-uploader .file-list');
  274. // let $list = document.querySelector('#global-uploader .file-list')
  275. // if ($list.style.display == '' && $list.style.display == 'none') {
  276. // $list.style.display == 'block';//显示
  277. // this.collapse = false;
  278. // // $list.slideUp();//隐藏
  279. // // this.collapse = true;
  280. // } else {
  281. // $list.style.display == 'none';//隐藏
  282. // this.collapse = true;
  283. // // $list.slideDown();//显示
  284. // // this.collapse = false;
  285. // }
  286. },
  287. close() {
  288. if(this.uploader.isUploading()) {
  289. this.$alert(
  290. "您有文件正在上传,关闭会中断上传,是否继续?",
  291. "提示",
  292. {
  293. confirmButtonText: "确定",
  294. callback: action => {
  295. console.log(action);
  296. if (action == "confirm") {
  297. this.uploader.cancel();
  298. this.panelShow = false;
  299. this.uploader.files = [];
  300. this.setUploaderList([]);
  301. Bus.$emit('modelStatusChange')
  302. } else { }
  303. }
  304. }
  305. );
  306. } else {
  307. this.uploader.cancel();
  308. this.panelShow = false;
  309. }
  310. },
  311. /**
  312. * 新增的自定义的状态: 'md5'、'transcoding'、'failed'
  313. * @param id
  314. * @param status
  315. */
  316. statusSet(id, status) {
  317. let statusMap = {
  318. md5: {
  319. text: '校验MD5',
  320. bgc: '#fff'
  321. },
  322. merging: {
  323. text: '合并中',
  324. bgc: '#e2eeff'
  325. },
  326. transcoding: {
  327. text: '转码中',
  328. bgc: '#e2eeff'
  329. },
  330. failed: {
  331. text: '上传失败',
  332. bgc: '#e2eeff'
  333. }
  334. }
  335. this.$nextTick(() => {
  336. let node = document.createElement("P");
  337. let att = document.createAttribute("class");
  338. att.value = `status_style myStatus_${id}`;
  339. let text = document.createTextNode(`${statusMap[status].text}`);
  340. node.appendChild(text);
  341. node.setAttributeNode(att);
  342. node.style.backgroundColor = `${statusMap[status].bgc}`
  343. document.querySelector(`.file_${id} .uploader-file-status`).appendChild(node);
  344. // $(`<p class="myStatus_${id}"></p>`).appendTo(`.file_${id} .uploader-file-status`).css({
  345. // 'position': 'absolute',
  346. // 'top': '0',
  347. // 'left': '0',
  348. // 'right': '0',
  349. // 'bottom': '0',
  350. // 'zIndex': '1',
  351. // 'backgroundColor': statusMap[status].bgc
  352. // }).text(statusMap[status].text);
  353. })
  354. },
  355. statusRemove(id) {
  356. this.$nextTick(() => {
  357. let dom = document.getElementsByClassName(`myStatus_${id}`)[0];
  358. dom.parentNode.removeChild(dom);
  359. })
  360. },
  361. error(msg) {
  362. this.$notify({
  363. title: '错误',
  364. message: msg,
  365. type: 'error',
  366. duration: 2000
  367. })
  368. }
  369. },
  370. watch: {},
  371. destroyed() {
  372. Bus.$off('openUploader');
  373. },
  374. components: {}
  375. }
  376. </script>
  377. <style scoped lang="scss">
  378. #global-uploader {
  379. position: fixed;
  380. z-index: 101;
  381. top: auto;
  382. right: 15px;
  383. bottom: 0;
  384. .uploader-app {
  385. width: 633px;
  386. }
  387. .file-panel {
  388. background-color: #fff;
  389. border: 1px solid #e2e2e2;
  390. border-radius: 7px 7px 0 0;
  391. box-shadow: 0 0 10px rgba(0, 0, 0, .2);
  392. .file-title {
  393. display: flex;
  394. height: 40px;
  395. line-height: 40px;
  396. padding: 0 15px;
  397. border-bottom: 1px solid #ddd;
  398. h2{
  399. font-size: 14px;
  400. font-style: normal;
  401. cursor: text;
  402. font-weight: 200;
  403. color: #666;
  404. }
  405. .operate {
  406. flex: 1;
  407. text-align: right;
  408. }
  409. }
  410. .file-list {
  411. position: relative;
  412. height: 350px;
  413. overflow-x: hidden;
  414. overflow-y: auto;
  415. background-color: #fff;
  416. /deep/ .el-scrollbar__wrap{
  417. overflow-x: hidden;
  418. }
  419. > li {
  420. background-color: #fff;
  421. }
  422. /deep/ .uploader-file-info i{
  423. display: none;
  424. }
  425. /deep/ .status_style{
  426. position: absolute;
  427. top: 0;
  428. left: 0;
  429. right: 0;
  430. bottom: 0;
  431. z-index: 1;
  432. }
  433. }
  434. // &.collapse {
  435. // .file-title {
  436. // background-color: #E7ECF2;
  437. // }
  438. // }
  439. }
  440. .no-file {
  441. position: absolute;
  442. top: 50%;
  443. left: 50%;
  444. transform: translate(-50%, -50%);
  445. font-size: 16px;
  446. text-align: center;
  447. }
  448. /deep/.uploader-file-icon {
  449. &:before {
  450. content: '' !important;
  451. }
  452. // &[icon=image] {
  453. // background: url(./images/image-icon.png);
  454. // }
  455. // &[icon=video] {
  456. // background: url(./images/video-icon.png);
  457. // }
  458. // &[icon=document] {
  459. // background: url(./images/text-icon.png);
  460. // }
  461. }
  462. /deep/ .uploader-file-actions > span {
  463. margin-right: 6px;
  464. }
  465. }
  466. /* 隐藏上传按钮 */
  467. #global-uploader-btn {
  468. position: absolute;
  469. clip: rect(0, 0, 0, 0);
  470. }
  471. </style>