@小程序上传图片
微信小程序上传图片
这是一个新手的学习心得, 小程序上传图片让我在百度找了好久, 最后终于找到了, 现将代码总结一下
//wxml中的代码
<view class='zhaopian' bindtap="chooseImage">
<image src='{{phone}}' data-index="{{index}}"></image>
<text>上传照片</text>
</view>
//在js中的代码
Page({
/**
* 页面的初始数据
*/
data: {
src:"../img/shenfenzheng.png",
src2: "../img/shenfenzheng-fan.png",
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
wx.setNavigationBarTitle({
title: '注册信息'
})
var that = this
// 点击上传图片
chooseImage(e) {
var that = this;
wx.chooseImage({
count: 1, //最多可以选择的图片总数
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为iqianshug标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
// console.log(tempFilePaths)
//启动上传等待中...
wx.showToast({
title: '正在上传...',
icon: 'loading',
mask: true,
duration: 10000
})
wx.uploadFile({
url: "www.baidu.com",//根据实际提供的接口
filePath: tempFilePaths[0],
name: 'pic',
formData: {//需要传的参数
openid: openid,
type: 2
},
header: {
"Content-Type": "multipart/form-data"
},
success: function(res) {
that.setData({
pageIndex: 1,
doctorArr: [],
src: JSON.parse(res.data).data.url,
// phone1: JSON.parse(res.data).url,
modelid: 1
}); // 重点
that.onLoad()
wx.showToast({
title: '成功',
icon: 'success',
duration: 2000,
})
},
fail: function(res) {
wx.hideToast();
wx.showModal({
title: '错误提示',
content: '上传图片失败',
showCancel: false,
success: function(res) {}
})
}
});
}
});
},
})