uniapp(微信小程序)上传图片到阿里oss

首先推荐下参考的文章

1.https://www.jianshu.com/p/34d6dcbdc2e5

2.https://help.aliyun.com/document_detail/92883.html?spm=a2c4g.11186623.6.670.5265350asB84kG

3.https://www.cnblogs.com/ziyoublog/p/13085217.html

遇到以下配置参数问题,才决定记录下

1.引入示例中的js文件时,有人报hmac.js 文件的 key = key.length + ..... 报错说这个length 找到不到。这个问题是你accesskey传值问题,可能是undefind.(确保在调用生成signature()方法时,accesskey能获取到)

我问题是policyBase64没有获取到,导致accesskey是undefind。

2.我使用的在阿里官网下载的base64.js等js文件,其中有个js文件包含window所以在小程序报错了。直接下载上面文章中js文件即可

3.上传成功了,但oss里面没有上传的图片。配置参数问题(路径错误,比较坑找了好久问题)

	// h5通过oss的简单上传接口
    const Oss = require('../../utils/aliyun-oss-sdk.min.js');
    // 小程序上传使用
	const Base64 = require('../../utils/base64.js');
	import Crypto from '../../utils/crypto.js'
	require('../../utils/hmac.js')
	require('../../utils/sha1.js')

    onLoad(options) {
        // 从后端获取oss配置参数:id/key      
        this.getOssConfig();
    },

			/**
			 * 获取oss配置项
			 */
			getOssConfig(){
				const params = {
					cmd: 'xxxx',
					cmd_op: 'xxxxxxxx',
				};
				this.$fetch('xxxx', 'POST', params, 'xxxxx').then((res)=>{
					if(res.data.code === 0){
						app.globalData.ossConfig = res.data.result;
                        // 获取base64
						this.getPolicyBase64();
					}
				}).catch(()=>{})
			},


			// 64(直接复制的)
			getPolicyBase64 () {
			  let date = new Date();
			  date.setHours(date.getHours() + 87600);
			  let srcT = date.toISOString();
			  const policyText = {
			    "expiration": srcT, //设置该Policy的失效时间
			    "conditions": [
			      ["content-length-range", 0, 5 * 1024 * 1024] // 设置上传文件的大小限制,5mb
			    ]
			  };
			  const policyBase64 = Base64.encode(JSON.stringify(policyText));
				this.policyBase64 = policyBase64;
                // 获取签名
				this.getSignature(policyBase64);
			},

			// 签名
			getSignature(policyBase64) {
				let ossData = app.globalData.ossConfig;
			  const accesskey = ossData.accessKey;
			  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
			    asBytes: true
			  });
			  const signature = Crypto.util.bytesToBase64(bytes);
				this.signature = signature;
			},


			/**
			 * 图片上传
			 */
			ChooseImage() {
				uni.chooseImage({
					count: 4, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图, 默认二者都有
					// sourceType: ['album'], //从相册选择, 默认二者都有
					success: (res) => {
						console.log('choose---res',res)
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
						}

                        // h5中使用
						// #ifdef H5
						// 上传oss
						res.tempFiles.forEach((item,index)=>{
							this.h5UrlToBlob(item.path).then((blobobj)=>{
								this.ossUplaod(item,blobobj)
							})
							this.uploadApi(item)
						})
						// #endif

                        // 非h5中使用
						// #ifndef H5
						res.tempFilePaths.forEach((item)=>{
							this.uploadApi(item)
						})
						// #endif
					}
				});
			},


			// uploadFileApi上传
            // item参数为tempFilePaths数组中的一项
			uploadApi(item){
				let ossData = app.globalData.ossConfig;
				let urlArr = ossData.url.split('//');
				let url = 'https://' + 'hite-jinkong.' + urlArr[1] + '/';
				let ossPath = ossData.path + item.replace('wxfile://', '');
				uni.uploadFile({
					url: url,
					filePath: item,
					name: 'file',
					formData: {
						name: item,
						key: ossPath,
						policy: this.policyBase64,
						OSSAccessKeyId: ossData.accessId,
						signature: this.signature,
						success_action_status: '200'
					},
					success(res) {
						this.uploaderUrl.push({
							picPath: '/' + ossPath,
							picUrl: url + ossPath
						});
						console.log('upload-success',url + ossPath)
					},
					fail(err) {
						console.error('err',err)
					}
				})
			},

h5上传到oss就简单了,转成blob对象即可。

 

			// 转化为blob类型格式
			h5UrlToBlob(url){
				console.log('url',url)
				return new Promise((resolve,reject)=>{
						var xhr = new XMLHttpRequest();
						xhr.open( 'GET', url, true);
						xhr.responseType = 'blob';
						xhr.onload = function( e) {
								if(this.status == 200) {
										var Blob = this.response;
										resolve(Blob)
										// myBlob现在是对象URL指向的blob。 
								}
						};
						xhr.send();
				})
			},

        	/**
			 * oss上传
			 */
			ossUplaod(item, blobobj){
				console.log('item',item)
				// 配置项
				let ossData = app.globalData.ossConfig;
				let client = new Oss({
					region: ossData.region,
					accessKeyId: ossData.accessId,
					accessKeySecret: ossData.accessKey,
					bucket: ossData.bucket
				})
				let fileNameArr = item.name.split('.');
				let fileName = fileNameArr[0] + new Date().getTime() + '.' + fileNameArr[1];
				let ossPath = '/' + ossData.path + fileName;
				console.log('ossData',ossData)
				client
					.put(ossPath, blobobj)
					.then((res) => {
						console.log('oss上传成功', res);
						this.uploaderUrl.push({
							picPath: ossPath,
							picUrl: res.url
						});
						this.tempPic.push({
							picPath: ossData.path,
							picName: fileName
						});
					})
					.catch((err) => {
						console.log('oss--err', err);
					});
			},

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章