需求:后端给前端一个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 = true
let that = this
// const OSS = require('ali-oss');
let path = e.tempFiles[0].file
console.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 = this
var 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 = undefined
let client = new OSS(res.data.data)
let storeAs = null
storeAs = '/bsh/' + timeMonth +
'/' + time + Math.ceil(Math.random() * 10000) + '.' + extname
client.put(storeAs, file).then(function(result) {
that.formData.imgUrl = result.url
that.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;
},