addFileTransmit.vue 15 KB

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