uniapp對接騰訊即時通訊TIM 發圖片消息問題

最近在用uniapp做app,中間涉及到了聊天功能,我在uni插件市場找到了集成tim騰訊即時通訊的模板:https://ext.dcloud.net.cn/plugin?id=1421

但作者沒有實現上傳圖片消息的功能,自己搞了下,坑真多

首先,uniapp中選擇圖片用uni.chooseImage,返回:

返回一些blob的url,但是tim要求發圖片必須使用dom對象或者File對象

 

這就只能把blob變成file對象了。

關於file對象的探索看這個:https://blog.csdn.net/lianzhang861/article/details/80283120

關於創建File對象,可以這樣:

var file1=new File([blob], "aa.png",{type:"image/jpg"}); //第一個參數是Blob對象或者dataUrl,第二個參數是文件名,三個參數可選,規定文件類型

注意:第一個參數必須是對象,不能是轉換成的字符串,比如uniapp或者微信小程序的chooseImage方法返回的blob的url,他是一個字符串,這樣生成的File對象只是將url字符串變成文件了,不是文件本身!!!

想把blob字符串變成Blob對象,可以用es6的:const blob = await fetch(image.path).then(r => r.blob())

或者用傳統的XHR或者ajax也行,就是把blob對象根據url給獲取出來就行。

實例:

getImage(type){
	this.hideDrawer();
	uni.chooseImage({
		sourceType:[type],
		sizeType: ['original'/* , 'compressed' */], //可以指定是原圖還是壓縮圖,默認二者都有
		success: (res)=>{
			console.log("!!!!!!!!!!!!!!!!!!!!")
			console.log(res)
			for(let i=0;i<res.tempFilePaths.length;i++){
				//res.name="aa.png"
				uni.getImageInfo({
					src: res.tempFilePaths[i],
					success: async  (image)=>{
						const blob = await fetch(image.path).then(r => r.blob())
						var file1=new File([blob], res.tempFiles[i].name,{type:blob.type});
						//file1.type="image/jpeg";
						let msg = {url:res.tempFilePaths[i],file:file1,w:image.width,h:image.height};
						this.sendMsg(msg,'img');
					}
				});
			}
		}
	});
},
// 發送消息
sendMsg(content,type){
	console.log(content)
	let message
	if(type=="text"){
		message= this.tim.createTextMessage({
		  to: this.toUserId,
		  conversationType: 'C2C',
		  payload: {
			text: content.text
		  }
		});	
	}else if(type=="img"){
		message = this.tim.createImageMessage({
		  to: this.toUserId,
		  conversationType: 'C2C',
		  // 消息優先級,用於羣聊(v2.4.2起支持)。如果某個羣的消息超過了頻率限制,後臺會優先下發高優先級的消息,詳細請參考:https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
		  // 支持的枚舉值:TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL(默認), TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
		  // priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
		  payload: {
			file: content.file
		  },
		  onProgress: function(event) { console.log('file uploading:', event) }
		});
	} 
	
	this.$store.commit('pushCurrentMessageList', message)
	let pomise = this.tim.sendMessage(message)
	pomise.then(res=>{
		console.log(res)
		this.$nextTick(()=> {
			// 滾動到底
			this.scrollToView = res.data.message.ID
		});
	})	
},

其實就是簡單的blob轉file而已,只不過從毫無頭緒開始搞起,又看jdk源碼都找資料的,一點點東西花了近兩天的時間!!!
 

 

 

 

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