useUploadFile.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { api_uploadAttachment } from "@/http/api.js"
  2. import Compressor from 'compressorjs';
  3. export function useUploadFile() {
  4. /**
  5. * 压缩
  6. */
  7. const toBlob = (canvas, imgObj) => {
  8. return new Promise((resolve,reject) => {
  9. canvas.toBlob((fileSrc) => {
  10. resolve(fileSrc)
  11. }, `${imgObj.fileType}/${imgObj.extname}`, 0.3)
  12. })
  13. }
  14. /**
  15. * 图片加载完成
  16. */
  17. const newImage = (img) => {
  18. return new Promise((resolve,reject) => {
  19. img.onload = () => {
  20. resolve()
  21. }
  22. })
  23. }
  24. /**
  25. * 压缩图片
  26. */
  27. const compressImage = (file) => {
  28. return new Promise((resolve,reject) => {
  29. new Compressor(file, {
  30. quality: 0.6, // 压缩质量,范围从0到1
  31. maxWidth: 1500, // 最大宽度
  32. maxHeight: 1500, // 最大高度
  33. success: (result) => {
  34. resolve(result); // 压缩后的图片
  35. },
  36. error: (err) => {
  37. reject(err); // 压缩失败的错误信息
  38. }
  39. });
  40. })
  41. }
  42. /**
  43. * 上传图片
  44. */
  45. const uploadFile = async (imgObj, type, incidentId, extra) => {
  46. console.log('44444', type)
  47. if(imgObj.extname=='mp4' || imgObj.extname=='avi' || imgObj.extname=='mpeg' ||
  48. imgObj.extname=='wmv' || imgObj.extname=='mov' || imgObj.extname=='3gp' ||
  49. imgObj.extname=='flv' || imgObj.extname=='mkv'){
  50. return uni.uploadFile({
  51. url: api_uploadAttachment(type, incidentId, extra),
  52. filePath: imgObj.path,
  53. name: 'file',
  54. formData: {
  55. 'filename': imgObj.name
  56. }
  57. })
  58. }else{
  59. const res = await uni.getImageInfo({src: imgObj.url});
  60. console.log('压缩前', res)
  61. let canvasWidth = res.width //图片原始长宽
  62. let canvasHeight = res.height
  63. let img = new Image()
  64. img.src = res.path
  65. let canvas = document.createElement('canvas');
  66. let ctx = canvas.getContext('2d')
  67. canvas.width = canvasWidth
  68. canvas.height = canvasHeight
  69. await newImage(img)
  70. ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight)
  71. const blob = await toBlob(canvas, imgObj)
  72. const fileSrc = await compressImage(blob)
  73. let tp = window.URL.createObjectURL(fileSrc)
  74. console.log('压缩后', tp);
  75. return uni.uploadFile({
  76. url: api_uploadAttachment(type, incidentId, extra),
  77. filePath: tp,
  78. name: 'file',
  79. formData: {
  80. 'filename': imgObj.name
  81. }
  82. });
  83. }
  84. }
  85. return {
  86. uploadFile
  87. };
  88. }