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

devtools/2024/10/11 13:21:36/

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

效果图

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

准备工作

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

1.html

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

2.javaScript

// 选择图片selectImg(e) {this.flag = truelet that = this// const OSS = require('ali-oss');let path = e.tempFiles[0].fileconsole.log(path,'path')const file = path;if (file) {that.compressImage(file, 1024, 0.2, (compressedBlob) => {const compressedFile = that.blobToFile(compressedBlob, file.name);// 这里拿到最终的File对象 compressedFile,可以用于上传等操作this.before(e.tempFiles[0].extname, compressedFile)});}},
/*** 压缩图片*/compressImage(file, maxWidth, quality, callback) {const reader = new FileReader();reader.onload = (e) => {const img = new Image();img.onload = () => {const canvas = document.createElement('canvas');const ctx = canvas.getContext('2d');let width = img.width;let height = img.height;if (width > maxWidth) {height = Math.round((height *= maxWidth / width));width = maxWidth;}canvas.width = width;canvas.height = height;ctx.drawImage(img, 0, 0, width, height);canvas.toBlob((blob) => {callback(blob);}, "image/jpeg", quality);};img.src = e.target.result;};reader.readAsDataURL(file);},
/*** 使用uni-file-picker选择图片文件。读取图片文件并将其转换为Image对象。使用一个Canvas元素来绘制并压缩图片。将压缩后的图片从Canvas中导出为Blob对象。将Blob转换为File对象。* */blobToFile(blob, fileName) {blob.lastModifiedDate = new Date();blob.name = fileName;return new File([blob], fileName, {type: blob.type});},
//  上传图片路径格式为https://oss-token-test.oss-cn-hangzhou.aliyuncs.com/qzzw/202402/2024022917120012345.png 202402为获取当前年月日 20240229171200为获取当前年月日时分秒 12345为随机数before(extname, file) {let that = thisvar timestamp = new Date().getTime()var time = this.havetime(timestamp)var timeMonth = this.haveMonth(timestamp)var haveMonthDay = this.haveMonthDay(timestamp)uni.request({url: 'http://sts.ck9696.com/oss/ckOSSServer/getCkOSSToken',method: 'post',data: {'exchangeTime': time,'channelId': '1','channelNo': '1','channelPassword': '1','appVersion': '1','appMobileModel': '1'},success: function(res) {uni.showToast({title: res,icon: 'none',duration: 2000})res.data.data.bucket = 'oss-token-test'res.data.data.endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'res.data.data.stsToken = res.data.data.securityToken// res.data.data.securityToken = undefinedlet client = new OSS(res.data.data)let storeAs = nullstoreAs = '/bsh/' + timeMonth +'/' + time + Math.ceil(Math.random() * 10000) + '.' + extnameclient.put(storeAs, file).then(function(result) {that.formData.imgUrl = result.urlthat.ImgUrl = [{url: result.url}]console.log(that.ImgUrl, 'that.ImgUrl')uni.setStorageSync('ImgUrl', that.ImgUrl);}).catch(function(err) {// console.log(JSON.stringify(err), 'errrrrrrrrrrrrrrrrrrrrrrrrrrrrr')})},fail: function(res) {uni.showToast({title: res,icon: 'none',duration: 2000})}})},
haveMonth(unixtime) {var date = new Date(unixtime);var y = date.getFullYear();var m = date.getMonth() + 1;m = m < 10 ? ('0' + m) : m;var d = date.getDate();d = d < 10 ? ('0' + d) : d;var h = date.getHours();h = h < 10 ? ('0' + h) : h;var minute = date.getMinutes();var second = date.getSeconds();minute = minute < 10 ? ('0' + minute) : minute;second = second < 10 ? ('0' + second) : second;return y + '' + m// return y + '-' + m + '-' + d + ' ' + h + ':' + minute;},


http://www.ppmy.cn/devtools/6608.html

相关文章

最新Java面试题3【2024中级】

互联网大厂面试题 1&#xff1a;阿里巴巴Java面试题 2&#xff1a;阿里云Java面试题-实习生岗 3&#xff1a;腾讯Java面试题-高级 4&#xff1a;字节跳动Java面试题 5&#xff1a;字节跳动Java面试题-大数据方向 6&#xff1a;百度Java面试题 7&#xff1a;蚂蚁金服Java…

Pytorch——训练时,冻结网络部分参数的方法

一、原理&#xff1a; 要固定训练网络的哪几层&#xff0c;只需要找到这几层参数(parameter)&#xff0c;然后将其 .requires_grad 属性设置为 False 。然后修改优化器&#xff0c;只将不被冻结的层传入。 二、效果 节省显存&#xff1a;不将不更新的参数传入optimizer提升速…

LeetCode 面试经典150题 202.快乐数

题目&#xff1a; 编写一个算法来判断一个数 n 是不是快乐数。 「快乐数」 定义为&#xff1a; 对于一个正整数&#xff0c;每一次将该数替换为它每个位置上的数字的平方和。然后重复这个过程直到这个数变为 1&#xff0c;也可能是 无限循环 但始终变不到 1。如果这个过程 结…

selenium反反爬虫,隐藏selenium特征

一、stealth.min.js 使用 用selenium爬网页时&#xff0c;常常碰到被检测到selenium &#xff0c;会被服务器直接判定为非法访问&#xff0c;这个时候就可以用stealth.min.js 来隐藏selenium特征&#xff0c;达到绕过检测的目的 from selenium import webdriver from seleniu…

OpenHarmony实战开发-如何通过分割swiper区域,实现指示器导航点位于swiper下方的效果。

介绍 本示例介绍通过分割swiper区域&#xff0c;实现指示器导航点位于swiper下方的效果。 效果预览图 使用说明 1.加载完成后swiper指示器导航点&#xff0c;位于显示内容下方。 实现思路 1.将swiper区域分割为两块区域&#xff0c;上方为内容区域&#xff0c;下方为空白区…

STM32 CAN接收FIFO细节

STM32 CAN接收FIFO细节 简介 CAN外设一共有2个接收FIFO&#xff0c;每个FIFO中有3个邮箱&#xff0c;即最多可以缓存6个接收到的报文。 FIFO状态 EMPTY: 初始状态&#xff0c;表示FIFO为空&#xff0c;没有挂起的消息&#xff08;FMP0x00&#xff09;&#xff0c;且没有发生…

【计算机网络】物理层

目录 物理层概述物理层接口特性 物理层下面的传输媒体导向型传输媒体非导向型传输媒体 传输方式串行传输和并行传输同步传输和异步传输单向通信&#xff0c;双向交替通信和双向同时通信 编码和调制编码与调制的基本概念常见编码方式 信道的极限容量&#xff08;不全&#xff0c…

ubuntu常用方法

文本文件的创建&#xff1a; sudo touch ubuntu.txt move clock: sudo chmod 777 ubuntu.txt 安装chrome wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb sudo apt install ./google-chrome-stable_current_amd64.deb .sh 文件的安装 例…