微信小程序实现图片上传和视频上传功能
服务器:阿里云
后端:PHP,提供上传接口
用到相关API:
wx.showActionSheet:显示操作菜单
wx.chooseImage:从本地相册选择图片或使用相机拍照,该api后期官方不维护,可使用 wx.chooseMedia api
wx.chooseVideo:拍摄视频或从手机相册中选视频
wx.chooseMedia:拍摄或从手机相册中选择图片或视频,官方提示:此接口不再更新,建议使用 wx.chooseMedia
选择需要上传的文件:
//可以选择视频或者图片
uploadFiles(){
var _this = this;
wx.showActionSheet({
itemList: ['选择图片', '选择视频'],
success: function (res) {
let xindex = res.tapIndex;
if (xindex == 0){
// 选择图片
_this.chooseImage()
} else if (xindex == 1){
// 选择视频
_this.chooseVideo()
}
},
fail: function (res) {
console.log(res.errMsg)
}
})
},
选择图片或拍照
// 选择图片类型
chooseImage(){
wx.chooseImage({
count: 1,//上传数量
sizeType: ['original', 'compressed'],//图片:原图和压缩
sourceType: ['album', 'camera'], // 选择图片的来源
success: (res) => {
let arr = res.tempFiles;
var imgInfo = {};
arr.map(function(v,i){
v['progress'] = 0;
imgInfo=v
})
_this.upImgs(imgInfo,'image')
}
})
},
选择视频或拍摄
chooseVideo(){
let _this=this
wx.chooseVideo({
count: 1,//上传数量
maxDuration:"30",//拍摄时长
sizeType: ['original', 'compressed'],//图片:原图和压缩
sourceType: ['album', 'camera'], // 选择图片的来源
// sourceType:"album",
compressed:true,
camera: 'back',
success: (res) => {
let videoInfo = {};
videoInfo['tempFilePath'] = res.tempFilePath;//路径
videoInfo['size'] = res.size;// 大小
videoInfo['height'] = res.height;
videoInfo['width'] = res.width;
videoInfo['thumbTempFilePath'] = res.thumbTempFilePath;//封面
videoInfo['progress'] = 0;
_this.upImgs(videoInfo,'video')
}
})
},
上传服务器
upImgs(dataInfo, type) {
let that=this
wx.showLoading({
title: '上传中',
mask:true,
})
wx.uploadFile({
url: '上传的网络地址',
filePath: type=='video'?dataInfo.tempFilePath:dataInfo.path,
formData:null,
name: 'file',
header: {
'content-type': 'multipart/form-data'
},
success:(res=>{
wx.hideLoading()
//判断上传的是图片还是视频
if(type=="video"){
that.setData({
console.log('视频地址:'+data.data.src)
console.log('视频封面:'+data.data.src+'?spm=qipa250&x-oss-process=video/snapshot,t_1000,f_jpg,w_800,h_400,m_fast')
}else{
console.log('图片地址:'+ data.data.src)
}
})
})
},