useUploadFile.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { api_uploadAttachment } from "@/http/api.js"
  2. export function useUploadFile() {
  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 uploadFile = async (imgObj, type, incidentId) => {
  27. console.log('44444', type)
  28. if(imgObj.extname=='mp4' || imgObj.extname=='avi' || imgObj.extname=='mpeg' || imgObj.extname=='wmv'){
  29. return uni.uploadFile({
  30. url: api_uploadAttachment(type, incidentId),
  31. filePath: imgObj.path,
  32. name: 'file',
  33. formData: {
  34. 'filename': imgObj.name
  35. }
  36. })
  37. }else{
  38. const res = await uni.getImageInfo({src: imgObj.url});
  39. console.log('压缩前', res)
  40. let canvasWidth = res.width //图片原始长宽
  41. let canvasHeight = res.height
  42. let img = new Image()
  43. img.src = res.path
  44. let canvas = document.createElement('canvas');
  45. let ctx = canvas.getContext('2d')
  46. canvas.width = canvasWidth
  47. canvas.height = canvasHeight
  48. await newImage(img)
  49. ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight)
  50. const fileSrc = await toBlob(canvas, imgObj)
  51. let tp = window.URL.createObjectURL(fileSrc)
  52. console.log('压缩后', tp);
  53. return uni.uploadFile({
  54. url: api_uploadAttachment(type, incidentId),
  55. filePath: tp,
  56. name: 'file',
  57. formData: {
  58. 'filename': imgObj.name
  59. }
  60. });
  61. }
  62. }
  63. return {
  64. uploadFile
  65. };
  66. }