微信小程序头像上传

一、html部分

<view class='head_img' bindtap='upShopLogo'>
    <text>头像</text>
    <view class='img'><image src='{{userimg}}'></image></view>
</view>

二、js部分

1.在data里面设置默认的值

data: {
    userimg:'',
    nickname:'',
},

2.点击事件触发上传事件

// 点击上传图片

	upShopLogo: function() {
		var that = this;
		wx.showActionSheet({
			itemList: ['从相册中选择', '拍照'],
			itemColor: "#f7982a",
			success: function(res) {
				if (!res.cancel) {
					if (res.tapIndex == 0) {
						that.chooseWxImageShop('album'); //从相册中选择
					} else if (res.tapIndex == 1) {
						that.chooseWxImageShop('camera'); //手机拍照
					}
				}
			}
		})
	},

3.选择图片

	chooseWxImageShop: function(type) {
		var that = this;
		wx.chooseImage({
			sizeType: ['original', 'compressed'],
			sourceType: [type],
			success: function(res) {
				that.data.userimg = res.tempFilePaths[0];
				that.upload_file(url, res.tempFilePaths[0]);
				userimg = res.tempFilePaths[0];
				that.setData({
					userimg: userimg
				})
			}
		})
	},

4.上传图片到服务器

	upload_file: function(url, filePath) {
		var that = this;
        var formData = {}; // HTTP 请求中其他额外的参数信息
		wx.uploadFile({
			url: url, //后台处理接口
			filePath: filePath,
			name: 'file',
			header: {
				'content-type': 'multipart/form-data'
			}, // 设置请求的 header
			formData:formData, 
			success: function(res) {
				var data = JSON.parse(res.data);
				that.setData({
					userimg: data.path,
				});
				that.showMessage('上传成功');
			},
			fail: function(res) {}
		})
	},


版权声明:本文为qq_35086913原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。