uploadFile.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { api_uploadAttachment } from "@/http/http.js"
  2. import Compressor from 'compressorjs';
  3. /**
  4. * 压缩
  5. */
  6. const toBlob = (canvas, imgObj) => {
  7. return new Promise((resolve,reject) => {
  8. canvas.toBlob((fileSrc) => {
  9. resolve(fileSrc)
  10. }, `${imgObj.fileType}/${imgObj.extname}`, 0.3)
  11. })
  12. }
  13. /**
  14. * 图片加载完成
  15. */
  16. const newImage = (img) => {
  17. return new Promise((resolve,reject) => {
  18. img.onload = () => {
  19. resolve()
  20. }
  21. })
  22. }
  23. /**
  24. * 压缩图片
  25. */
  26. const compressImage = (file) => {
  27. return new Promise((resolve,reject) => {
  28. new Compressor(file, {
  29. quality: 0.6, // 压缩质量,范围从0到1
  30. maxWidth: 1500, // 最大宽度
  31. maxHeight: 1500, // 最大高度
  32. success: (result) => {
  33. resolve(result); // 压缩后的图片
  34. },
  35. error: (err) => {
  36. reject(err); // 压缩失败的错误信息
  37. }
  38. });
  39. })
  40. }
  41. /**
  42. * 上传图片
  43. */
  44. export const uploadFile = async (imgObj, type, incidentId) => {
  45. console.log('44444', type)
  46. if(imgObj.extname=='mp4' || imgObj.extname=='avi' || imgObj.extname=='mpeg' ||
  47. imgObj.extname=='wmv' || imgObj.extname=='mov' || imgObj.extname=='3gp' ||
  48. imgObj.extname=='flv' || imgObj.extname=='mkv'){
  49. return uni.uploadFile({
  50. url: api_uploadAttachment(type, incidentId),
  51. filePath: imgObj.path,
  52. name: 'file',
  53. formData: {
  54. 'filename': imgObj.name
  55. }
  56. })
  57. }else{
  58. const res1 = await uni.getImageInfo({src: imgObj.url});
  59. const res = res1[1];
  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. timeout: 600000,
  77. url: api_uploadAttachment(type, incidentId),
  78. filePath: tp,
  79. name: 'file',
  80. formData: {
  81. 'filename': imgObj.name
  82. }
  83. });
  84. }
  85. }