前言
现在的项目是用的vue+uniapp搭建的,之前做了一个需求是选择图片上传的功能,后面遇到了二期优化是需要支持图片➕视频上传的功能。
正文
第一期的需求是支持图片上传,可以用 uni.chooseImage(OBJECT) 这个API用来选择图片并上传,但是需要注意chooseImage在移动端是限制了只能选图片的,但是在pc的浏览器运行时是可以选择任意其他文件类型的,所以需要对file.type做限制,否则在pc浏览器可以上传任意文件。
第二期的需求是支持图片视频上传,查了一下uniapp的官方文档第一想法是用 uni.chooseMedia(OBJECT) 这个API,结果发现这个API只支持在小程序上运行,h5是不支持的?
继续查了一下uniapp的其他API,看到了上传文件这个 uni.chooseFile(OBJECT) API,但是官方给出的建议是用于选择非媒体文件,选择媒体文件的有3个专用API,图片选择跟视频选择还是分开的。
最后采用了以下方案,选择上传文件的时候让用户多一层交互选择(视频/图片),再分别调用chooseImage或者chooseVideo让用户选择对应的多媒体~
用户点击上传按钮时,调用以下方法弹出对应的选择弹窗让用户选择上传类型
chooseVideoImage(){ uni.showActionSheet({ title:"选择上传类型", itemList: ['图片','视频'], success: (res) => { console.log(res) if(res.tapIndex == 0){ this.chooseImages() } else { this.chooseVideo() } } })},
选择图片方法
chooseImages () { var ths = this; wx.chooseImage({ count: 1, // 默认9 sizeType: ['compressed'], sourceType: ['album', 'camera'], success: function (res) { // 图片的本地临时文件路径列表 this.files = res // var tempFilePaths = res.tempFilePaths; uni.showLoading({ mask: true }); this.files.tempFiles.forEach(file => { console.log('file', file); const isSize = file.size / (1024 * 1024) < 20 if (!isSize) { uni.showToast({ title: '图片必须小于20M', icon: 'none', }) return false } const imgType = file.type === 'image/png' || file.type === 'image/jpeg' if (!imgType) { uni.showToast({ title: '图片仅限png/jpg', icon: 'none', }) return false } }) } }); },
选择视频方法
chooseVideo() { var ths = this; uni.chooseVideo({ maxDuration:10, count: 1, // 默认9 compressed: true, sourceType: ['album', 'camera'], success: async function (res) { // 图片的本地临时文件路径列表 this.files = res console.log(this.files, 'files'); // var tempFilePaths = res.tempFilePaths; uni.showLoading({ mask: true }); let file = this.files.tempFile const isSize = file.size / (1024 * 1024) < 20 if (!isSize) { uni.showToast({ title: '视频小于20M', icon: 'none', }) return false } const imgType = file.type === 'video/mp4' || 'video/quicktime' // video/quicktime 兼容ios上传视频格式 if (!imgType) { uni.showToast({ title: '视频格式不对', icon: 'none', }) return false } } });},
小结
有时候换种方式也能很好的解决问题~
相关链接
https://uniapp.dcloud.io/api/media/file
https://uniapp.dcloud.io/api/media/image?id=chooseimage
https://uniapp.dcloud.io/api/media/video?id=choosevideo
https://uniapp.dcloud.io/api/media/video?id=choosemedia