开始是使用uniapp自带的组件上传文件,但是没有达到我预期的效果,使用uni.chooseImage,uni.chooseVideo这两个方法,也是踩了一点坑的;h5使用起来完全没有问题,但是在App上面两个方法返回的值是完全不一样的。所以就封装了两个方法针对h5和App兼容处理
export const uploadChooseVideo = (extension = ['mp4', 'avi', 'mov']) => new Promise((resolve, reject) => {
uni.chooseVideo({
extension,
success: res => {
// #ifdef H5
const type = res.tempFile.type;
if (!type.includes('video')) return Toast('请上传视频');
// #endif
const screenWidth = systemInfo().screenWidth;
const aspect = res.width / res.height;
const videoWidth = screenWidth + 'rpx'
const videoheight = (screenWidth / aspect) + 'rpx'
resolve({
tempFilePath: res.tempFilePath,
videoWidth, videoheight
})
},
fail: err => {
Toast('上传失败');
reject(err)
}
})
})
上面这是针对uniapp视频h5、App的兼容处理。
其中 systemInfo() 这个是 uni.getSystemInfoSync()的返回值,因为全局会有很多地方会用到所以就提出来了。Toast这个方法是一个提示框这个可以根据你们自己的封装去实现这里就不贴出来了
export const uploadChooseImage = (count = 9) => new Promise((resolve, reject) => {
uni.chooseImage({
count,
sizeType: ['compressed'],
success: res => {
if (count == 1) {
const tempFilePath = res.tempFilePaths[0];
const tempFile = res.tempFiles[0]
return resolve({ tempFilePath, tempFile })
}
return resolve(res)
},
fail: err => {
Toast('上传失败');
reject(err)
}
})
})
// 下面的是使用方法
async chooseImage() {
const res = await uploadChooseImage();
if (res.errMsg == 'chooseImage:ok') {
const { tempFilePaths, tempFiles } = res;
if (this.uploadImage.length < 9) {
for (let index = 0; index < tempFilePaths.length; index++) {
const item = tempFilePaths[index];
// #ifdef H5
const type = tempFiles[index].type
if (!type.includes('image')) {
Toast('请上传图片')
break;
}
// #endif
try {
const result = await this.getuploadImage(item)
if (result) {
this.uploadImage = [...this.uploadImage, item];
if (this.uploadImage.length == 9) {
break;
}
}
} catch (error) {
Toast('上传失败')
}
}
}
}
},
这是对图片的封装,针对图片的逻辑根据自己的逻辑进行处理。
这是一套完整的聊天软件如有需要项目源码的可进行留言