服务器怎么使用融云发图片消息,融云发送文件和图片消息

融云发送文件和图片消息

前段时间集成了web端融云的聊天功能,但是只能发送普通消息,最近产品经理出了新需求,需要把文件发送和图片发送加上,那就撸起袖子走一遍。

看过文档之后,才发现发送文件和图片消息是分两步的,首先要实现文件和图片的上传,然后拿到数据后发送消息。融云默认是存储到七牛服务器的,其实也可以上传到自己的服务器,由于是个demo,我暂时就存储到七牛啦。

文件和图片上传

上传暂时还不支持npm的引如方式,需要在html中引入上截图中的三个文件,顺序如下:

然后在input的change事件中,触发以下方法:fileChange(evt, type) {

this.currentType = type === 'img' ? RongIMLib.FileType.IMAGE : RongIMLib.FileType.FILE;

const file = evt.target.files[0];

console.log('file', file);

if (type === 'img') {

UploadClient.initImage(this.config, (uploadFile) => { // 上传文件为: UploadClient.initFile

uploadFile.upload(file, this.uploadCallbacks);

});

} else {

UploadClient.initFile(this.config, (uploadFile) => {

uploadFile.upload(file, this.uploadCallbacks);

});

}

},

config配置如下:config() {

return {

domain: 'http://upload.qiniu.com',

fileType: this.currentType,

getToken: (callback) => {

this.rongIMClient.getFileToken(this.currentType , {

onSuccess: (data) => {

callback(data.token);

},

onError: () => {

console.error('get file token error', error);

}

});

}

}

},

成功回调配置如下:uploadCallbacks() {

return {

onProgress: (loaded, total) => {

const percent = Math.floor(loaded / total * 100);

console.log('已上传: ', percent);

},

onCompleted: (data) => {

this.currentFile = data;

this.getFileUrl(data);

},

onError: (error) => {

console.error('上传失败', error);

}

}

},

注:如果是图片的话在onCompleted里面通过data.thumbnail是可以拿到图片的缩略图的。

接下来是获取文件或者图片的url,也需要在onComplete回调中获取,代码如下:getFileUrl(data) {

if (data.thumbnail) {

this.currentFile.base64 = `data:image/jpg;base64,${data.thumbnail`;

}

this.rongIMClient.getFileUrl(this.currentType, data.filename, data.name, {

onSuccess: (data) => {

this.currentFile = Object.assign(this.currentFile, data);

this.sendFileMessage(this.currentType);

console.log('文件 url 为: ', data);

},

onError: function(error) {

console.log('get file url error', error);

}

})

},

拿到文件或者图片的url之后就可以发送图片或者文件消息了。

文件和图片消息发送

发消息代码如下:sendFileMessage(type) {

let msg = {};

if (type === RongIMLib.FileType.IMAGE) {

msg = new RongIMLib.ImageMessage({content: this.currentFile.base64, imageUri: this.currentFile.downloadUrl});

} else {

msg = new RongIMLib.FileMessage({name: this.currentFile.name, size: this.currentFile.size, type: this.currentFile.type, fileUrl: this.currentFile.downloadUrl});

}

var conversationType = this.targetUser.conversationType;

var targetId = this.targetUser.id; // 目标 Id

var callback = {

onSuccess: (message) => {

this.handleMessage(message);

},

onError: (errorCode) => {

}

};

this.rongIMClient.sendMessage(conversationType, targetId, msg, callback);

},

至此,发送图片和文件消息完成,整体算是顺利……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值