小程序上传图片

选择器

wx.chooseImage官方参数文档链接:https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html

changeavatar(){
  var _this = this;
  wx.showActionSheet({
  itemList: ['拍照', '从相册上传'],
  itemColor:'#333',
  success(res) {
  console.log(res.tapIndex)
  if(res.tapIndex == 0){
  wx.chooseImage({
  count: 1,//最多可以选择的图片张数,默认9
  sizeType: ['original', 'compressed'],//original 原图,compressed 压缩图,默认二者都有
  sourceType: ['camera'],// album 从相册选图,camera 使用相机,默认二者都有
  success: function(res) {
  const tempFilePaths = res.tempFilePaths;
  _this.updateHead(tempFilePaths[0]);
  },
  fail: function (res) {//接口调用失败的回调函数
  console.log(res)
  },
  complete: function (res) {//接口调用结束的回调函数(调用成功、失败都会执行)
  console.log(res)
  }
  })
  } else if (res.tapIndex == 1){
  wx.chooseImage({
  count: 1,//最多可以选择的图片张数,默认9
  sizeType: ['original', 'compressed'],//original 原图,compressed 压缩图,默认二者都有
  sourceType: ['album'],// album 从相册选图,camera 使用相机,默认二者都有
  success: function (res) {
  const tempFilePaths = res.tempFilePaths;
  _this.updateHead(tempFilePaths[0]);
  },
  fail: function (res) {//接口调用失败的回调函数
  console.log(res)
  },
  complete: function (res) {//接口调用结束的回调函数(调用成功、失败都会执行)
  console.log(res)
  }
  })
  }
  },
  fail(res) {
  console.log(res.errMsg)
  }
  })
},
 
 
 
 
图片或文件上传代码
 
//修改头像
updateHead: function (fliePath){
var _this = this;
//验证token
var token = wx.getStorageSync('token');
if (!token) {
wx.redirectTo({
url: '../login/login',
})
}
//选择上传
wx.uploadFile({
url: globleData.basePathUrl +'userhead_edit.rm',//服务器路径
filePath: fliePath,//文件路径
name: 'userHead_file',//自定义名称
header:{
"Content-Type": "multipart/form-data",//上传类型设置
'token': token
},
formData:{},
success:function(res){
console.log(res);
if(res.statusCode == 200){
var data = JSON.parse(res.data);//这里返回data为字符串 转成对象
if (data.code == 100){//服务器code判断
var userHead = data.object;
var userData = _this.data.userData;
userData.userHead = userHead;
//修改本页数据
_this.setData({
userData: userData,
})
wx.showToast({
title: '成功',
icon: 'success',
duration: 2000
})
}else{
wx.showToast({
title: '失败',
icon: 'fail',
duration: 2000
})
}
}else{
wx.showToast({
title: '失败',
icon: 'fail',
duration: 2000
})
}
},
fail:function(res){
wx.showToast({
title:'失败',
icon:'fail',
duration:2000
})
},
complete:function(){

}
})
}
posted @ 2019-07-29 17:46  9102  阅读(281)  评论(0编辑  收藏  举报