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

需求:后端给前端一个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;
			},

  • 13
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将图片上传到腾讯云OSS,你需要进行以下步骤: 1. 在腾讯云中创建一个对象存储桶(Bucket)。 2. 在uniapp中安装并引入腾讯云OSS SDK。 3. 编写上传代码,包括以下步骤: - 获取上传凭证:在腾讯云中创建一个临时的密钥,用于上传图片。 - 创建上传任务:使用SDK提供的uploadObject方法,将图片进行上传。 - 监听上传进度:可以使用SDK提供的progress方法,获取上传进度信息。 这是一个示例代码,可以帮助你更好地理解上传图片到腾讯云OSS的过程: ```javascript import COS from "cos-wx-sdk-v5"; const cos = new COS({ getAuthorization: async function (options, callback) { try { // 获取上传凭证 const res = await uni.request({ url: "上传凭证接口", method: "GET", }); const { credentials } = res.data; callback({ TmpSecretId: credentials.tmpSecretId, TmpSecretKey: credentials.tmpSecretKey, SecurityToken: credentials.sessionToken, StartTime: credentials.startTime, ExpiredTime: credentials.expiredTime, }); } catch (err) { console.log(err); } }, }); export default { methods: { async uploadFile(file, fileName) { try { // 创建上传任务 const res = await new Promise((resolve, reject) => { cos.uploadObject( { Bucket: "你的Bucket名称", Region: "你的Bucket所在地域", Key: fileName, FilePath: file.path, }, function (err, data) { if (err) { reject(err); } else { resolve(data); } } ).on("progress", function (info) { console.log(info.percent * 100 + "%"); }); }); console.log(res); } catch (err) { console.log(err); } }, }, }; ``` 这段代码中,首先引入了腾讯云OSS SDK,并创建了一个COS实例。在上传文件的方法中,首先调用了 `getAuthorization` 方法获取上传凭证,然后使用 `cos.uploadObject` 方法创建上传任务。同时,也可以使用 `on` 方法监听上传进度,以便实时更新上传进度。最后,上传完成后,会返回上传成功的信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值