轻量应用服务器搭建网站/网络公司网络营销推广方案
废话不多说,直接上代码。我这里是mpvue的写法,可能与原生的小程序有部分不一样的,请注意。
// 选择图片
avatarChoose() {var that = this wx.showActionSheet({itemList: ['从手机相册选择'],success: function(res) {//选择照片 wx.chooseImage({count: 1, // 选择图片张数,默认9sizeType: ['compressed'], // 可以指定是原图original还是压缩图compressed,默认二者都有sourceType: ['album'], // 可以指定来源是相册还是相机,默认二者都有success: function (res) {console.info(res)var size = res.tempFiles[0].size //获取图片的大小,单位Bvar path = res.tempFiles[0].path;var formatImage = path.split(".")[(path.split(".")).length - 1];if(size > 1024*1024){ //图片大于指定大小时,提示错误that.errorMsg = '图片超出1M大小'res.tempFiles[0] = nullres.tempFilePaths[0] = null}else if (formatImage != "png" && formatImage != "jpg" && formatImage != "jpeg") { //判断图片类型,实际上在手机上操作不需要这一步判断that.errorMsg = '图片格式只支持png、jpg、jpeg'res.tempFiles[0] = nullres.tempFilePaths[0] = null}else{ var tempFilePaths = res.tempFilePaths[0] //不能传数组,要获取下标0的图片 that.pageForm.avatar = tempFilePaths //把图片的临时路径赋值给我们定义好的变量that.errorMsg = '' //将错误提示置空}}})}})
},
onSubmit(values) {let that = this // 必要的参数合法性验证,此处省略wx.uploadFile({ //上传文件固定用法,不要使用 wx.requesturl: that.baseUrl+'xxx', //后台url,需要在微信公众号平台的uploadFile配置https的域名filePath: that.pageForm.avatar, //图片路径method: 'POST',//方法POST、PUT、DELETE、GETname: 'file', //后台获取的凭据,与后台一致header: {"Content-Type":"multipart/form-data;charset=utf-8" //上传文件的请求头,固定写法},formData: that.pageForm,//其它参数success (res) { //上传成功console.info(res)//其它逻辑请自行添加,比如页面跳转,弹出提示框等}, fail: function (res) { //上传失败console.error(res)Toast('操作失败') }})
},
页面上引用
<!--其它字段省略,可自行添加-->
<!--实现图片预览-->
<div class="avatar" @click="avatarChoose"><img :src="pageForm.avatar"/>
</div>
<!--提交-->
<button class="btn" @click="onSubmit">立即提交</button>