addFileTransmit.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. <template>
  2. <view class="main">
  3. <view class="bg-white default_title">
  4. <u--form :model="inputForm" labelWidth="130px" class="u-form default_title" labelPosition="left"
  5. ref="inputForm">
  6. <u-form-item label="年度" borderBottom prop="yearNum">
  7. <u--input readonly v-model="inputForm.yearNum" placeholder="输入年度" border="none"></u--input>
  8. </u-form-item>
  9. <u-form-item label="卡号" borderBottom prop="cardNum">
  10. <u--input readonly v-model="inputForm.cardNum" placeholder="输入卡号" border="none"></u--input>
  11. </u-form-item>
  12. </u--form>
  13. </view>
  14. <view class="bg-white margin-top main_info">
  15. <u--form :model="inputForm" :rules="rules" labelWidth="130px" class="u-form default_title"
  16. labelPosition="left" ref="inputForm">
  17. <u-form-item required label="来文机关" borderBottom prop="sendingAgency">
  18. <u--input v-model="inputForm.sendingAgency" placeholder="请输入来文机关" border="none"></u--input>
  19. </u-form-item>
  20. <u-form-item label="来文字号" borderBottom prop="docFontSize">
  21. <u--input v-model="inputForm.docFontSize" placeholder="请输入来文字号" border="none"></u--input>
  22. </u-form-item>
  23. <u-form-item label="文件来源" borderBottom prop="fileSource">
  24. <u--input v-model="inputForm.fileSource" placeholder="请输入文件来源" border="none"></u--input>
  25. </u-form-item>
  26. <u-form-item label="成文时间" borderBottom prop="writtenTime">
  27. <jp-datetime-picker :show="iswrite" v-model="inputForm.writtenTime" placeholder="选择成文时间"
  28. mode="date"></jp-datetime-picker>
  29. </u-form-item>
  30. <u-form-item label="收文时间" borderBottom prop="receivingTime">
  31. <jp-datetime-picker :show="isreceive" v-model="inputForm.receivingTime" placeholder="选择收文时间"
  32. mode="date"></jp-datetime-picker>
  33. </u-form-item>
  34. <u-form-item required label="内容摘要" borderBottom prop="contentSummary">
  35. <u--textarea v-model="inputForm.contentSummary" placeholder="请输入内容摘要" border="none"></u--textarea>
  36. </u-form-item>
  37. <u-form-item label="来文附件" prop="attachedDocumentId" labelPosition="top">
  38. <lsj-upload ref="lsjUpload" childId="upload1" width="250rpx" height="200rpx" :option="option"
  39. :debug="false" :instantly="false" @uploadEnd="onuploadEnd" @change="afterRead">
  40. <view class="addfile flex">
  41. <u-icon size="20" bold name="plus"></u-icon>
  42. </view>
  43. </lsj-upload>
  44. <!-- #ifdef H5 -->
  45. <view class="takephoto addfile flex" @click="takePhoto"> <u-icon size="20" bold
  46. name="camera"></u-icon>
  47. </view>
  48. <!-- #endif -->
  49. </u-form-item>
  50. <view class="text-danger" style="font-size: 12px!important;">请确保上传图片内容清晰可见,所有涉密敏感信息不得上传</view>
  51. <view class="other_info">
  52. <view class="other_pdf">
  53. <u-cell-group>
  54. <u-cell v-for="item in fileList" >
  55. <view slot="title">
  56. <u--text :lines="1" :text="item.name"></u--text>
  57. </view>
  58. <u-icon slot="value" size="28" name="trash-fill" @click="deleteFile(item)"></u-icon>
  59. </u-cell>
  60. </u-cell-group>
  61. </view>
  62. </view>
  63. <u-upload :fileList="imgList" @delete="deletePic" multiple :maxCount="imgList.length"
  64. :previewFullImage="true"></u-upload>
  65. <view class="submit_btn flex">
  66. <u-button v-if="!loading" type="primary" text="提交新增" @click="formSubmit"></u-button>
  67. <u-button v-if="loading" :loading="loading" type="primary" text="加载中"></u-button>
  68. </view>
  69. </u--form>
  70. </view>
  71. <u-toast ref="uToast"></u-toast>
  72. <u-overlay :show="loading">
  73. <view class="warp">
  74. <view class="rect"><u-button plain loading loadingText="加载中"></u-button></view>
  75. </view>
  76. </u-overlay>
  77. </view>
  78. </template>
  79. <script>
  80. import {
  81. isImageFormat
  82. } from "@/common/util.js"
  83. import BASE_URL from '@/config.js'
  84. import moment from "moment/moment"
  85. import * as $auth from "@/common/auth.js"
  86. import fileService from '@/api/file/fileService.js'
  87. import gwCirculationCard2Service from '@/api/circulation/gwCirculationCard2.js'
  88. export default {
  89. mounted() {
  90. gwCirculationCard2Service.getCardNum().then(data => {
  91. const currentYear = new Date().getFullYear();
  92. this.inputForm.yearNum = currentYear
  93. this.cardNum = data
  94. this.inputForm.cardNum = "[" + currentYear + "]" + data + "号"
  95. this.inputForm.writtenTime = moment().format('YYYY-MM-DD');
  96. this.inputForm.receivingTime = moment().format('YYYY-MM-DD');
  97. })
  98. },
  99. data() {
  100. return {
  101. imgsrc: {},
  102. loading: false,
  103. isreceive: false,
  104. iswrite: false,
  105. fileLists: [],
  106. files: [],
  107. fileList: [],
  108. imgList: [],
  109. cardNum: "",
  110. inputForm: {
  111. id: '',
  112. yearNum: '',
  113. cardNum: '',
  114. sendingAgency: '',
  115. docFontSize: '',
  116. fileSource: '',
  117. writtenTime: '',
  118. receivingTime: '',
  119. contentSummary: '',
  120. attachedDocumentId: '',
  121. remark: '',
  122. state: '1'
  123. },
  124. rules: {
  125. sendingAgency: [{
  126. required: true,
  127. message: '请输入来问机关',
  128. trigger: ['blur', 'change']
  129. }],
  130. contentSummary: [{
  131. required: true,
  132. message: '请输入内容摘要',
  133. trigger: ['blur', 'change']
  134. }]
  135. },
  136. // 上传接口参数
  137. option: {
  138. url: BASE_URL + '/gwfile/upload?uploadPath=filetransmit',
  139. name: 'file',
  140. header: {
  141. "token": $auth.getUserToken()
  142. },
  143. },
  144. }
  145. },
  146. methods: {
  147. showToast(params) {
  148. this.loading = false
  149. this.$refs.uToast.show({
  150. ...params,
  151. complete() {
  152. params.url && uni.redirectTo({
  153. url: params.url
  154. })
  155. }
  156. })
  157. },
  158. // 删除文件
  159. deleteFile(item) {
  160. let that = this
  161. that.fileList = that.fileList.filter(i => !(i.url == item.url))
  162. that.fileLists = that.fileLists.filter(i => !(i.url == item.url))
  163. },
  164. // 删除图片
  165. deletePic(event) {
  166. let that = this
  167. this.imgList = this.imgList.filter(item => item.name != event.file.name)
  168. that.fileLists = that.fileLists.filter(i => !(i.name == event.file.name))
  169. },
  170. // 图片压缩
  171. compressH5(urlData, targetSizeKB, initialQuality = 1.0) {
  172. const maxQuality = 1.0;
  173. const minQuality = 0.0;
  174. const tolerance = 0.01; // 根据需要调整公差
  175. if (!urlData.url) {
  176. this.$set(urlData, "url", urlData.path)
  177. }
  178. let that = this
  179. return new Promise((resolve, reject) => {
  180. let binarySearch = (min, max) => {
  181. const midQuality = (min + max) / 2;
  182. uni.getImageInfo({
  183. src: urlData.url,
  184. success(res) {
  185. const reader = new FileReader();
  186. let img = new Image()
  187. img.src = res.path
  188. img.onload = function() {
  189. const canvas = document.createElement('canvas');
  190. const ctx = canvas.getContext('2d');
  191. canvas.width = img.width;
  192. canvas.height = img.height;
  193. ctx.clearRect(0, 0, canvas.width, canvas.height);
  194. ctx.drawImage(img, 0, 0, canvas.width, canvas
  195. .height);
  196. // 使用异步的 toBlob 方法
  197. canvas.toBlob(async (blob) => {
  198. const fileSizeKB = blob.size /
  199. 1024;
  200. if (Math.abs(fileSizeKB -
  201. targetSizeKB) <
  202. tolerance || max - min <
  203. tolerance) {
  204. // 当前质量足够接近目标大小,使用当前质量解析
  205. reader.readAsDataURL(blob);
  206. reader.onload = () => {
  207. let result = that
  208. .uploadFilePromise(reader
  209. .result)
  210. setTimeout(() => {
  211. resolve(result)
  212. }, 300)
  213. }
  214. } else if (fileSizeKB >
  215. targetSizeKB) {
  216. // 如果文件大小太大,降低质量,继续二分查找
  217. binarySearch(min, midQuality);
  218. } else {
  219. // 如果文件大小太小,增加质量,继续二分查找
  220. binarySearch(midQuality, max);
  221. }
  222. }, urlData.type, midQuality);
  223. };
  224. }
  225. })
  226. }
  227. // 开始二分查找
  228. binarySearch(minQuality, maxQuality);
  229. })
  230. },
  231. // 拍照
  232. takePhoto() {
  233. let that = this
  234. // 调用uniapp的chooseImage API 选择图片
  235. uni.chooseImage({
  236. count: 1, // 默认9, 设置图片的数量
  237. sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
  238. sourceType: ['camera'], // 可以指定来源是相册还是相机,默认二者都有
  239. success: (chooseImageRes) => {
  240. uni.showLoading({
  241. title: "上传中"
  242. })
  243. const tempFilePaths = chooseImageRes.tempFiles[0];
  244. // 成功选择图片后进行压缩处理
  245. that.compressH5(tempFilePaths, 150).then(result => {
  246. const fileName = result.split(/[/\\=]/).pop();
  247. let item1 = {
  248. name: fileName,
  249. url: BASE_URL + result
  250. }
  251. let item = {
  252. name: fileName,
  253. path: result,
  254. }
  255. that.fileLists.push(item)
  256. that.imgList.push(item1)
  257. uni.hideLoading()
  258. })
  259. },
  260. fail: (error) => {
  261. uni.hideLoading()
  262. }
  263. });
  264. },
  265. // 拍照上传
  266. async uploadFilePromise(param) {
  267. return new Promise((resolve, reject) => {
  268. let a = uni.uploadFile({
  269. url: this.BASE_URL + '/gwfile/upload?uploadPath=filetransmit',
  270. filePath: param,
  271. name: 'file',
  272. header: {
  273. "token": $auth.getUserToken()
  274. },
  275. success: (res) => {
  276. setTimeout(() => {
  277. resolve(res.data)
  278. }, 300)
  279. }
  280. })
  281. });
  282. },
  283. // 新增图片
  284. afterRead(files) {
  285. uni.showLoading({
  286. title: "上传中"
  287. })
  288. let lists = [...files.values()]
  289. this.files = files
  290. for (let i = 0; i < lists.length; i++) {
  291. if (lists[i].type == 'success') continue;
  292. if (isImageFormat(lists[i].name) && lists[i].size > 200 * 1024) {
  293. this.compressAPP(lists[i], 150).then(res => {
  294. this.files.get(lists[i].name).file = res
  295. this.upload(lists[i].name)
  296. })
  297. } else {
  298. this.upload(lists[i].name)
  299. }
  300. }
  301. },
  302. // app图片压缩
  303. compressAPP(urlData, targetSizeKB, initialQuality = 1.0) {
  304. const maxQuality = 1.0;
  305. const minQuality = 0.0;
  306. const tolerance = 0.01; // 根据需要调整公差
  307. let that = this
  308. return new Promise((resolve, reject) => {
  309. let binarySearch = (min, max) => {
  310. const midQuality = (min + max) / 2;
  311. uni.getImageInfo({
  312. src: urlData.path,
  313. success: function(res) {
  314. let img = new Image()
  315. img.src = res.path
  316. img.onload = function() {
  317. const canvas = document.createElement('canvas');
  318. const ctx = canvas.getContext('2d');
  319. canvas.width = img.width;
  320. canvas.height = img.height;
  321. ctx.clearRect(0, 0, canvas.width, canvas.height);
  322. ctx.drawImage(img, 0, 0, canvas.width, canvas
  323. .height);
  324. // 使用异步的 toBlob 方法
  325. canvas.toBlob(async (blob) => {
  326. const fileSizeKB = blob.size / 1024;
  327. if (Math.abs(fileSizeKB -
  328. targetSizeKB) <
  329. tolerance || max - min <
  330. tolerance) {
  331. // 当前质量足够接近目标大小,使用当前质量解析
  332. const file = new File([blob], urlData
  333. .name, {
  334. type: blob.type,
  335. lastModified: new Date()
  336. .getTime(), // 使用当前时间作为最后修改时间
  337. });
  338. setTimeout(() => {
  339. resolve(file)
  340. }, 300)
  341. } else if (fileSizeKB >
  342. targetSizeKB) {
  343. // 如果文件大小太大,降低质量,继续二分查找
  344. binarySearch(min, midQuality);
  345. } else {
  346. // 如果文件大小太小,增加质量,继续二分查找
  347. binarySearch(midQuality, max);
  348. }
  349. }, urlData.file.type, midQuality);
  350. };
  351. },
  352. fail: function(err) {
  353. resolve(false);
  354. }
  355. });
  356. }
  357. // 开始二分查找
  358. binarySearch(minQuality, maxQuality);
  359. })
  360. },
  361. // APP手动上传
  362. upload(name) {
  363. // name=指定文件名,不指定则上传所有type等于waiting和fail的文件
  364. this.$refs['lsjUpload'].upload(name);
  365. },
  366. onuploadEnd(item) {
  367. console.log(`${item.name}已上传结束,上传状态=${item.type}`);
  368. // 更新当前窗口状态变化的文件
  369. this.files.set(item.name, item);
  370. let file = {
  371. name: item.name,
  372. path: item.responseText
  373. }
  374. this.fileLists.push(file)
  375. const fileName = item.name.split(/[/\\=]/).pop();
  376. if (isImageFormat(item.name)) {
  377. let item1 = {
  378. name: fileName,
  379. url: this.BASE_URL + item.responseText
  380. }
  381. this.imgList.push(item1)
  382. } else {
  383. let a = {
  384. name: fileName,
  385. url: this.BASE_URL + item.responseText
  386. }
  387. this.fileList.push(a)
  388. }
  389. uni.hideLoading()
  390. // 微信小程序Map对象for循环不显示,所以转成普通数组,
  391. // 如果你用不惯Map对象,也可以像这样转普通数组,组件使用Map主要是避免反复文件去重操作
  392. // #ifdef MP-WEIXIN
  393. this.wxFiles = [...this.files.values()];
  394. // #endif
  395. // 强制更新视图
  396. this.$forceUpdate();
  397. // ---可删除--演示判断是否所有文件均已上传成功
  398. let isAll = [...this.files.values()].find(item => item.type !== 'success');
  399. if (!isAll) {
  400. } else {
  401. console.log(isAll.name + '待上传');
  402. }
  403. },
  404. // 下载文件
  405. download(param) {
  406. fileService.download(param).then(data)
  407. },
  408. // 表单提交
  409. formSubmit() {
  410. this.loading = true
  411. let auditForm = Object.assign({}, this.inputForm);
  412. let files = []
  413. console.log("this.fileLists==>", this.fileLists);
  414. this.fileLists.forEach(item => {
  415. files.push(item.path)
  416. })
  417. auditForm.attachedDocumentId = files.join(",");
  418. auditForm.writtenTime = auditForm.writtenTime + " 00:00:00";
  419. auditForm.receivingTime = auditForm.receivingTime + " 00:00:00";
  420. auditForm.cardNum = this.cardNum
  421. this.$refs.inputForm.validate().then(valid => {
  422. if (valid) {
  423. gwCirculationCard2Service.save(auditForm).then((data) => {
  424. let param = {
  425. type: 'success',
  426. message: data,
  427. iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png',
  428. url: "/pages/index/index"
  429. }
  430. this.showToast(param);
  431. }).catch(() => {
  432. let param = {
  433. type: 'error',
  434. message: data,
  435. iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png',
  436. }
  437. this.showToast(param);
  438. })
  439. }
  440. }).catch(e => {
  441. this.loading = false
  442. })
  443. }
  444. }
  445. }
  446. </script>
  447. <style>
  448. .warp {
  449. display: flex;
  450. align-items: center;
  451. justify-content: center;
  452. height: 100%;
  453. }
  454. .default_title {
  455. padding-top: 0px;
  456. }
  457. .main_info {
  458. margin-top: 15px;
  459. }
  460. .u-form-item__body__right__message span {
  461. font-size: 12px !important;
  462. }
  463. .submit_btn {
  464. background-color: #fefefe;
  465. margin-top: 20px;
  466. box-shadow: none;
  467. margin-bottom: 20px;
  468. }
  469. .submit_btn button {
  470. height: 40px;
  471. width: 80%;
  472. border-radius: 50px;
  473. }
  474. .addfile {
  475. width: 80px;
  476. height: 80px;
  477. background-color: #eee;
  478. padding-left: 24%;
  479. margin: 10px;
  480. }
  481. .takephoto {
  482. padding-left: 9%;
  483. }
  484. .other_info {
  485. width: 100%;
  486. }
  487. </style>