uniapp 小程序上传图片/音频到oss

//选择图片
			chooseHeadUrl() {
				let that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
					success: function(res) {
						// console.log(JSON.stringify(res.tempFilePaths));
						// that.data.portraitUri = res.tempFilePaths[0]
						that.portraitUri = res.tempFilePaths[0]
						// console.log(that.portraitUri)
					}
				})
			},
			//上传图片OSS
			uploadOss(path) {
				return new Promise((resolve, reject) => {
					let that = this
					let reg = RegExp(/mp3/)
					let format = '.jpg'
					let location = 'image'
					if (reg.test(path)) {
						format = '.mp3'
						location = 'audio'
					}
					let position = 'tcell/' + location + '/'
					getPolicyPrivate(position).then((res) => {
						// console.log(res)
						// 向后台发请求 拉取OSS相关配置
						const creds = res[1].data.data;
						//随机数
						function randomString(length) {
							var str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
							var result = "";
							for (var i = length; i > 0; --i) {
								result += str[Math.floor(Math.random() * str.length)];
							}
							return result + (new Date()).valueOf();
						}
						const SJS = randomString(6);
						uni.uploadFile({
							url: creds.host, // 开发者服务器的URL。
							filePath: path,
							name: 'file', // 必须填file。	
							formData: {
								key: position + SJS + format,
								policy: creds.policy,
								OSSAccessKeyId: creds.accessid,
								signature: creds.signature,
							},
							success: (res) => {
								// console.log(res)
								that.data.portraitUri = creds.host + '/' + position + SJS + format
								resolve('提交成功')
								// console.log(that.data.portraitUri + '666')
								// console.log(res,'oss')
							},
							fail: err => {
								console.log(err);
								reject('未选择头像')
							}
						})
					})
				})
			},

注:个人备忘所用

你可能感兴趣的:(uni-app,小程序)