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);
					});
			},

 

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