My_upload.vue 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. <template>
  2. <!-- 模板部分保持不变 -->
  3. <view v-if="custom">
  4. <up-upload @after-read="afterRead" :deletable="!disabled" @delete="deletePic"
  5. :max-count="disabled ? fileList.length : maxCount" :accept="accept" multiple @clickPreview="clickPreview">
  6. <slot />
  7. </up-upload>
  8. </view>
  9. <up-upload v-else :fileList="fileList" @after-read="afterRead" :deletable="!disabled" @delete="deletePic"
  10. :max-count="disabled ? fileList.length : maxCount" :accept="accept" multiple @clickPreview="clickPreview" />
  11. </template>
  12. <script setup>
  13. import { ref, reactive, defineProps, defineEmits, getCurrentInstance, onUnmounted } from 'vue'
  14. const emit = defineEmits(['uploadCallback', 'startUploading'])
  15. const props = defineProps({
  16. accept: {
  17. type: String,
  18. default: "image"
  19. },
  20. maxCount: {
  21. type: [String, Number],
  22. default: 99
  23. },
  24. uploadCallback: {
  25. type: Function
  26. },
  27. startUploading: {
  28. type: Function
  29. },
  30. fileList: {
  31. type: Array,
  32. default: reactive([])
  33. },
  34. usetype: {
  35. type: String,
  36. default: 'default'
  37. },
  38. ownertable: {
  39. type: String,
  40. default: 'temporary'
  41. },
  42. ownerid: {
  43. type: [String, Number],
  44. default: 1
  45. },
  46. disabled: {
  47. type: Boolean,
  48. default: false
  49. },
  50. custom: {
  51. type: Boolean,
  52. default: false
  53. },
  54. // 新增压缩相关配置
  55. compressConfig: {
  56. type: Object,
  57. default: () => ({
  58. enable: true, // 是否启用压缩
  59. maxSize: 1024 * 1024, // 1MB,超过此大小才压缩(单位:字节)
  60. maxWidth: 1920, // 最大宽度
  61. maxHeight: 1080, // 最大高度
  62. quality: 0.8, // 图片质量 0-1
  63. videoBitrate: 1000000, // 视频比特率 1Mbps
  64. videoMaxWidth: 1280, // 视频最大宽度
  65. videoMaxHeight: 720 // 视频最大高度
  66. })
  67. }
  68. })
  69. const { $Http } = getCurrentInstance().proxy;
  70. const deleteList = reactive([]); // 用于存储待删除的文件列表
  71. const clickPreview = (e) => {
  72. uni.previewImage({
  73. urls: props.fileList.map(v => v.url),
  74. current: e.url,
  75. loop: true,
  76. })
  77. }
  78. // 判断是否为图片
  79. const isImage = (file) => {
  80. return file.type?.startsWith('image/') ||
  81. /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(file.name) ||
  82. /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(file.url);
  83. }
  84. // 判断是否为视频
  85. const isVideo = (file) => {
  86. return file.type?.startsWith('video/') ||
  87. /\.(mp4|mov|avi|wmv|flv|mkv|webm)$/i.test(file.name) ||
  88. /\.(mp4|mov|avi|wmv|flv|mkv|webm)$/i.test(file.url);
  89. }
  90. // H5平台压缩图片
  91. const compressImageH5 = (file) => {
  92. return new Promise((resolve, reject) => {
  93. const img = new Image();
  94. img.crossOrigin = 'Anonymous';
  95. img.onload = () => {
  96. const canvas = document.createElement('canvas');
  97. const ctx = canvas.getContext('2d');
  98. // 计算压缩后的尺寸
  99. let width = img.width;
  100. let height = img.height;
  101. if (width > props.compressConfig.maxWidth || height > props.compressConfig.maxHeight) {
  102. const ratio = Math.min(
  103. props.compressConfig.maxWidth / width,
  104. props.compressConfig.maxHeight / height
  105. );
  106. width = Math.floor(width * ratio);
  107. height = Math.floor(height * ratio);
  108. }
  109. canvas.width = width;
  110. canvas.height = height;
  111. // 填充白色背景(对于透明图片)
  112. ctx.fillStyle = '#FFFFFF';
  113. ctx.fillRect(0, 0, width, height);
  114. // 绘制图片
  115. ctx.drawImage(img, 0, 0, width, height);
  116. // 转换为Blob
  117. canvas.toBlob((blob) => {
  118. resolve(blob);
  119. }, file.type || 'image/jpeg', props.compressConfig.quality);
  120. };
  121. img.onerror = reject;
  122. // 创建Object URL
  123. if (file.url.startsWith('blob:')) {
  124. img.src = file.url;
  125. } else if (file.originFileObj) {
  126. img.src = URL.createObjectURL(file.originFileObj);
  127. } else {
  128. img.src = file.url;
  129. }
  130. });
  131. }
  132. // H5平台压缩视频(使用MediaRecorder API)
  133. const compressVideoH5 = (file) => {
  134. return new Promise((resolve, reject) => {
  135. const video = document.createElement('video');
  136. video.preload = 'metadata';
  137. video.onloadedmetadata = () => {
  138. // 计算压缩后的尺寸
  139. let width = video.videoWidth;
  140. let height = video.videoHeight;
  141. if (width > props.compressConfig.videoMaxWidth || height > props.compressConfig.videoMaxHeight) {
  142. const ratio = Math.min(
  143. props.compressConfig.videoMaxWidth / width,
  144. props.compressConfig.videoMaxHeight / height
  145. );
  146. width = Math.floor(width * ratio);
  147. height = Math.floor(height * ratio);
  148. }
  149. // 创建Canvas来捕获视频帧
  150. const canvas = document.createElement('canvas');
  151. canvas.width = width;
  152. canvas.height = height;
  153. const ctx = canvas.getContext('2d');
  154. // 设置视频尺寸
  155. video.width = width;
  156. video.height = height;
  157. // 开始捕获视频(这里简化处理,实际应用中可能需要使用MediaRecorder)
  158. // 注意:完整视频压缩需要更复杂的实现,这里只做演示
  159. video.onseeked = () => {
  160. ctx.drawImage(video, 0, 0, width, height);
  161. canvas.toBlob((blob) => {
  162. // 这里应该压缩整个视频,而不是单帧
  163. // 实际项目中建议使用第三方库或服务端压缩
  164. resolve(blob);
  165. }, 'video/mp4');
  166. };
  167. video.currentTime = 0;
  168. };
  169. video.onerror = reject;
  170. if (file.url.startsWith('blob:')) {
  171. video.src = file.url;
  172. } else if (file.originFileObj) {
  173. video.src = URL.createObjectURL(file.originFileObj);
  174. } else {
  175. video.src = file.url;
  176. }
  177. });
  178. }
  179. // 小程序/App平台压缩图片
  180. const compressImageNative = (file) => {
  181. return new Promise((resolve, reject) => {
  182. uni.compressImage({
  183. src: file.url,
  184. quality: props.compressConfig.quality * 100, // 转换为百分比
  185. success: (res) => {
  186. console.log('图片压缩成功', res);
  187. resolve(res.tempFilePath);
  188. },
  189. fail: (err) => {
  190. console.error('图片压缩失败', err);
  191. // 压缩失败时使用原文件
  192. resolve(file.url);
  193. }
  194. });
  195. });
  196. }
  197. // 小程序/App平台压缩视频
  198. const compressVideoNative = (file) => {
  199. return new Promise((resolve, reject) => {
  200. uni.compressVideo({
  201. src: file.url,
  202. quality: 'medium', // low, medium, high
  203. bitrate: props.compressConfig.videoBitrate,
  204. fps: 30,
  205. resolution: props.compressConfig.videoMaxHeight,
  206. success: (res) => {
  207. console.log('视频压缩成功', res);
  208. resolve(res.tempFilePath);
  209. },
  210. fail: (err) => {
  211. console.error('视频压缩失败', err);
  212. // 压缩失败时使用原文件
  213. resolve(file.url);
  214. }
  215. });
  216. });
  217. }
  218. // 压缩文件处理
  219. const compressFile = async (file) => {
  220. try {
  221. // 检查是否启用压缩
  222. if (!props.compressConfig.enable) {
  223. return file;
  224. }
  225. // 检查文件大小,小于阈值不压缩
  226. let fileSize = file.size;
  227. // 如果在H5环境,获取文件大小
  228. if (!fileSize && file.originFileObj) {
  229. fileSize = file.originFileObj.size;
  230. }
  231. // 如果无法获取大小,默认压缩
  232. if (!fileSize || fileSize > props.compressConfig.maxSize) {
  233. let compressedUrl;
  234. // #ifdef H5
  235. if (isImage(file)) {
  236. const blob = await compressImageH5(file);
  237. compressedUrl = URL.createObjectURL(blob);
  238. file.compressedSize = blob.size;
  239. } else if (isVideo(file)) {
  240. // H5视频压缩需要专门的库,这里简化处理
  241. console.warn('H5视频压缩需要专门的库,暂使用原文件');
  242. compressedUrl = file.url;
  243. }
  244. // #endif
  245. // #ifndef H5
  246. if (isImage(file)) {
  247. compressedUrl = await compressImageNative(file);
  248. } else if (isVideo(file)) {
  249. compressedUrl = await compressVideoNative(file);
  250. }
  251. // #endif
  252. if (compressedUrl && compressedUrl !== file.url) {
  253. return {
  254. ...file,
  255. url: compressedUrl,
  256. compressed: true
  257. };
  258. }
  259. }
  260. return file;
  261. } catch (error) {
  262. console.error('压缩文件失败:', error);
  263. // 压缩失败返回原文件
  264. return file;
  265. }
  266. }
  267. // 文件读取后处理(修改后)
  268. const afterRead = async ({ file }) => {
  269. emit('startUploading', file);
  270. for (const item of file) {
  271. try {
  272. // 压缩处理
  273. const compressedFile = await compressFile(item);
  274. // #ifdef H5
  275. const arrayBuffer = await getArrayBuffer(compressedFile);
  276. arrayBuffer.data.url = compressedFile.url;
  277. handleUploadFile(requestType(compressedFile), arrayBuffer.data);
  278. // 更新文件列表状态
  279. props.fileList.push({
  280. ...compressedFile,
  281. status: 'uploading',
  282. message: '上传中',
  283. });
  284. // #endif
  285. // #ifndef H5
  286. uni.getFileSystemManager().readFile({
  287. filePath: compressedFile.url,
  288. success: data => {
  289. data.data.url = compressedFile.url;
  290. handleUploadFile(requestType(compressedFile), data.data);
  291. // 更新文件列表状态
  292. props.fileList.push({
  293. ...compressedFile,
  294. status: 'uploading',
  295. message: '上传中',
  296. });
  297. },
  298. fail: console.error
  299. });
  300. // #endif
  301. } catch (error) {
  302. console.error('处理文件失败:', error);
  303. uni.showToast({
  304. title: '文件处理失败',
  305. icon: 'none'
  306. });
  307. }
  308. }
  309. }
  310. // 获取文件类型信息
  311. const requestType = (file) => {
  312. let ext = ''
  313. // #ifdef H5
  314. ext = file.name.substring(file.name.lastIndexOf(".") + 1)
  315. // #endif
  316. // #ifndef H5
  317. ext = file.type?.split("/")[1] ||
  318. file.url.substring(file.url.lastIndexOf(".") + 1) ||
  319. file.name.substring(file.name.lastIndexOf(".") + 1)
  320. // #endif
  321. return {
  322. id: '10019701',
  323. "content": {
  324. "filename": `${Date.now() + (file.size || 0)}.${ext}`,
  325. "filetype": ext,
  326. "parentid": uni.getStorageSync('siteP').appfolderid
  327. }
  328. }
  329. }
  330. // 获取ArrayBuffer (H5专用) - 修改以支持压缩后的文件
  331. const getArrayBuffer = (file) => {
  332. return new Promise((resolve, reject) => {
  333. // 如果是压缩后的文件且是Blob URL
  334. if (file.url.startsWith('blob:')) {
  335. fetch(file.url)
  336. .then(response => response.blob())
  337. .then(blob => {
  338. const reader = new FileReader();
  339. reader.readAsArrayBuffer(blob);
  340. reader.onload = () => resolve({
  341. data: reader.result,
  342. compressed: file.compressed
  343. });
  344. reader.onerror = error => reject(error);
  345. })
  346. .catch(reject);
  347. } else {
  348. // 原逻辑
  349. const xhr = new XMLHttpRequest()
  350. xhr.open('GET', file.url, true)
  351. xhr.responseType = 'blob'
  352. xhr.onload = function () {
  353. if (this.status === 200) {
  354. const myBlob = this.response
  355. const files = new File(
  356. [myBlob],
  357. file.name,
  358. { type: file.type },
  359. )
  360. const reader = new FileReader()
  361. reader.readAsArrayBuffer(files)
  362. reader.onload = () => resolve({
  363. data: reader.result,
  364. compressed: file.compressed
  365. })
  366. reader.onerror = error => reject(error)
  367. } else {
  368. reject(`文件加载失败: ${this.status}`)
  369. }
  370. }
  371. xhr.onerror = () => reject('网络请求失败')
  372. xhr.send()
  373. }
  374. })
  375. }
  376. // 处理文件上传
  377. const handleUploadFile = (file, data) => {
  378. $Http.basic(file).then(res => {
  379. console.log("上传文件成功", res)
  380. if (res.msg == "成功") {
  381. uploadFile(res.data, data)
  382. } else {
  383. uni.showToast({
  384. title: `${file.content.filename}上传失败`,
  385. icon: "none"
  386. })
  387. }
  388. })
  389. }
  390. // 上传文件到服务器
  391. const uploadFile = (res, data) => {
  392. uni.request({
  393. url: res.uploadurl,
  394. method: "PUT",
  395. data,
  396. header: { 'Content-Type': 'application/octet-stream' },
  397. success: () => {
  398. $Http.basic({
  399. id: 10019901,
  400. "content": { "serialfilename": res.serialfilename }
  401. }).then(s => {
  402. console.log("文件上传反馈", s)
  403. handleFileLink([{
  404. attachmentid: s.data.attachmentids[0],
  405. url: data.url
  406. }], "temporary", 1, props.usetype)
  407. }).catch(console.error)
  408. },
  409. fail: console.error
  410. })
  411. }
  412. function handleFileLink(list, ownertable = "temporary", ownerid = 1, usetype = 'default', resolve = () => { }) {
  413. if (list.length == 0) return resolve(true);
  414. let content = {
  415. ownertable,
  416. ownerid,
  417. usetype,
  418. attachmentids: list.map(v => v.attachmentid),
  419. siteid: uni.getStorageSync("userMsg").siteid
  420. }
  421. $Http.basic({
  422. "classname": "system.attachment.Attachment",
  423. "method": "createFileLink",
  424. content
  425. }).then(res => {
  426. console.log('跟进记录绑定附件', res)
  427. resolve(res.code == '1')
  428. if (res.code != '1') return uni.showToast({
  429. title: res.msg,
  430. icon: "none"
  431. })
  432. list.forEach(v => {
  433. const file = props.fileList.find(s => v.url === s.url || v.url === s.thumb);
  434. if (file) {
  435. delete file.status;
  436. delete file.message;
  437. Object.assign(file, res.data.find(s => s.attachmentid === v.attachmentid));
  438. }
  439. });
  440. emit('uploadCallback', { fileList: props.fileList, attachmentids: content.attachmentids })
  441. })
  442. }
  443. // 保存所有的附件绑定到表上,有在上传的文件不能保存
  444. const isUploading = (showToast = true) => {
  445. let res = props.fileList.some(file => file.status === 'uploading');
  446. if (res && showToast) uni.showToast({
  447. title: '文件正在上传中,请稍后再试',
  448. icon: 'none'
  449. });
  450. return res
  451. }
  452. // 保存接口 接受数据调用handleFileLink
  453. const saveFileLinks = (ownertable, ownerid, usetype = 'default') => {
  454. // 如果有待删除的文件,先删除
  455. deleteList.length && deleteFile(deleteList);
  456. return new Promise((resolve, reject) => {
  457. const list = props.fileList;
  458. console.log("list", list)
  459. if (list.length) {
  460. return handleFileLink(list, ownertable, ownerid, usetype, resolve);
  461. } else {
  462. resolve(true)
  463. }
  464. })
  465. }
  466. function deletePic({ file, index, name }) {
  467. uni.showModal({
  468. cancelText: '取消',
  469. confirmText: '删除',
  470. content: '是否确定删除该文件?',
  471. title: '提示',
  472. success: ({ confirm }) => {
  473. if (confirm) {
  474. console.log("删除文件", file);
  475. if (file.ownertable == 'temporary') {
  476. // 临时文件直接删除
  477. deleteFile([file]).then(res => {
  478. if (res) {
  479. props.fileList.splice(index, 1);
  480. emit('uploadCallback', { fileList: props.fileList });
  481. }
  482. })
  483. } else {
  484. deleteList.push(file)
  485. props.fileList.splice(index, 1);
  486. emit('uploadCallback', { fileList: props.fileList })
  487. }
  488. }
  489. },
  490. })
  491. }
  492. // 直接删除文件
  493. const deleteFile = (arr) => {
  494. return new Promise((resolve, reject) => {
  495. let list = arr.filter(file => file.linksid);
  496. if (list.length) {
  497. $Http.basic({
  498. "classname": "system.attachment.Attachment",
  499. "method": "deleteFileLink",
  500. "content": {
  501. linksids: list.map(v => v.linksid),
  502. }
  503. }).then(res => {
  504. console.log("删除文件", res);
  505. resolve(res.code == 1)
  506. if (res.code != 1) uni.showToast({
  507. title: res.msg,
  508. icon: "none"
  509. })
  510. })
  511. } else {
  512. resolve(true)
  513. }
  514. })
  515. }
  516. // 清空临时文件 ownertable == 'temporary'
  517. const clearTemporaryFiles = (arr = props.fileList) => {
  518. let list = arr.filter(file => file.ownertable == 'temporary' && file.linksid);
  519. if (list.length) $Http.basic({
  520. "classname": "system.attachment.Attachment",
  521. "method": "deleteFileLink",
  522. "content": {
  523. linksids: list.map(v => v.linksid),
  524. }
  525. }).then(res => {
  526. console.log("清空临时文件", res);
  527. })
  528. }
  529. // 在页面销毁的时候 自动清空所有的临时文件
  530. onUnmounted(() => {
  531. // 清理压缩产生的临时URL(H5)
  532. // #ifdef H5
  533. props.fileList.forEach(file => {
  534. if (file.compressed && file.url.startsWith('blob:')) {
  535. URL.revokeObjectURL(file.url);
  536. }
  537. });
  538. // #endif
  539. clearTemporaryFiles();
  540. })
  541. defineExpose({ isUploading, handleFileLink, saveFileLinks, deleteFile })
  542. </script>