0


uniapp h5项目上传图片到oss(纯前端)

需求:后端给前端一个oss上传地址,前端需要根据getCkOSSToken获取stsToken,使用client.put方法将图片上传成功,并且使用canvas压缩图片

效果图

废话不多说,直接上代码,代码可直接复制,运行

准备工作

  1. cnpm install ali-oss --save
  2. 在需要的页面引入
  3. import OSS from 'ali-oss'

1.html

  1. <view class="" style="margin-top: 20rpx;">
  2. <uni-file-picker limit="1" title="" @select="selectImg" @delete="deletePic" :sizeType="sizeType"
  3. ></uni-file-picker>
  4. </view>

2.javaScript

  1. // 选择图片
  2. selectImg(e) {
  3. this.flag = true
  4. let that = this
  5. // const OSS = require('ali-oss');
  6. let path = e.tempFiles[0].file
  7. console.log(path,'path')
  8. const file = path;
  9. if (file) {
  10. that.compressImage(file, 1024, 0.2, (compressedBlob) => {
  11. const compressedFile = that.blobToFile(compressedBlob, file.name);
  12. // 这里拿到最终的File对象 compressedFile,可以用于上传等操作
  13. this.before(e.tempFiles[0].extname, compressedFile)
  14. });
  15. }
  16. },
  17. /**
  18. * 压缩图片
  19. */
  20. compressImage(file, maxWidth, quality, callback) {
  21. const reader = new FileReader();
  22. reader.onload = (e) => {
  23. const img = new Image();
  24. img.onload = () => {
  25. const canvas = document.createElement('canvas');
  26. const ctx = canvas.getContext('2d');
  27. let width = img.width;
  28. let height = img.height;
  29. if (width > maxWidth) {
  30. height = Math.round((height *= maxWidth / width));
  31. width = maxWidth;
  32. }
  33. canvas.width = width;
  34. canvas.height = height;
  35. ctx.drawImage(img, 0, 0, width, height);
  36. canvas.toBlob((blob) => {
  37. callback(blob);
  38. }, "image/jpeg", quality);
  39. };
  40. img.src = e.target.result;
  41. };
  42. reader.readAsDataURL(file);
  43. },
  44. /**
  45. * 使用uni-file-picker选择图片文件。
  46. 读取图片文件并将其转换为Image对象。
  47. 使用一个Canvas元素来绘制并压缩图片。
  48. 将压缩后的图片从Canvas中导出为Blob对象。
  49. 将Blob转换为File对象。
  50. *
  51. */
  52. blobToFile(blob, fileName) {
  53. blob.lastModifiedDate = new Date();
  54. blob.name = fileName;
  55. return new File([blob], fileName, {
  56. type: blob.type
  57. });
  58. },
  59. // 上传图片路径格式为https://oss-token-test.oss-cn-hangzhou.aliyuncs.com/qzzw/202402/2024022917120012345.png 202402为获取当前年月日 20240229171200为获取当前年月日时分秒 12345为随机数
  60. before(extname, file) {
  61. let that = this
  62. var timestamp = new Date().getTime()
  63. var time = this.havetime(timestamp)
  64. var timeMonth = this.haveMonth(timestamp)
  65. var haveMonthDay = this.haveMonthDay(timestamp)
  66. uni.request({
  67. url: 'http://sts.ck9696.com/oss/ckOSSServer/getCkOSSToken',
  68. method: 'post',
  69. data: {
  70. 'exchangeTime': time,
  71. 'channelId': '1',
  72. 'channelNo': '1',
  73. 'channelPassword': '1',
  74. 'appVersion': '1',
  75. 'appMobileModel': '1'
  76. },
  77. success: function(res) {
  78. uni.showToast({
  79. title: res,
  80. icon: 'none',
  81. duration: 2000
  82. })
  83. res.data.data.bucket = 'oss-token-test'
  84. res.data.data.endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
  85. res.data.data.stsToken = res.data.data.securityToken
  86. // res.data.data.securityToken = undefined
  87. let client = new OSS(res.data.data)
  88. let storeAs = null
  89. storeAs = '/bsh/' + timeMonth +
  90. '/' + time + Math.ceil(Math.random() * 10000) + '.' + extname
  91. client.put(storeAs, file).then(function(result) {
  92. that.formData.imgUrl = result.url
  93. that.ImgUrl = [{
  94. url: result.url
  95. }]
  96. console.log(that.ImgUrl, 'that.ImgUrl')
  97. uni.setStorageSync('ImgUrl', that.ImgUrl);
  98. }).catch(function(err) {
  99. // console.log(JSON.stringify(err), 'errrrrrrrrrrrrrrrrrrrrrrrrrrrrr')
  100. })
  101. },
  102. fail: function(res) {
  103. uni.showToast({
  104. title: res,
  105. icon: 'none',
  106. duration: 2000
  107. })
  108. }
  109. })
  110. },
  111. haveMonth(unixtime) {
  112. var date = new Date(unixtime);
  113. var y = date.getFullYear();
  114. var m = date.getMonth() + 1;
  115. m = m < 10 ? ('0' + m) : m;
  116. var d = date.getDate();
  117. d = d < 10 ? ('0' + d) : d;
  118. var h = date.getHours();
  119. h = h < 10 ? ('0' + h) : h;
  120. var minute = date.getMinutes();
  121. var second = date.getSeconds();
  122. minute = minute < 10 ? ('0' + minute) : minute;
  123. second = second < 10 ? ('0' + second) : second;
  124. return y + '' + m
  125. // return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
  126. },
标签: uni-app 前端 uv

本文转载自: https://blog.csdn.net/m0_72929120/article/details/137828278
版权归原作者 00秃头小宝贝 所有, 如有侵权,请联系我们删除。

“uniapp h5项目上传图片到oss(纯前端)”的评论:

还没有评论