作者:用户geafr1kx8g | 来源:互联网 | 2024-11-04 12:51
在微信小程序中,图片上传功能是开发者常用的功能之一。本文详细介绍了`wx.chooseImage`和`wx.uploadFile`的使用方法及注意事项。通过`wx.chooseImage`,用户可以选择本地图片或拍摄新照片,而`wx.uploadFile`则用于将选中的图片上传到服务器。文章还提供了代码示例,帮助开发者更好地理解和应用这两个API。此外,文中还讨论了常见的错误处理和性能优化技巧,确保图片上传过程的稳定性和高效性。
bindtap='getImage'>image>
<text>相册text>
view>
<view class='photo-image-wrap photo-image-wrap2'>
<image src='/images/photo1.png' bindtap='takePhoto'>image>
<text>拍摄text>
view>
<navigator url='/pages/index/index'>
<image src='/images/close1.png' class='close'>image>
navigator>
view>
view>
wxss:
.container{
width: 750rpx;
height: 100%;
position: relative;
}
.photo-wrap{
width: 750rpx;
height: 420rpx;
text-align: center;
position: fixed;
bottom: 0rpx;
}
.photo-image-wrap{
width: 196rpx;
height: 260rpx;
}
.photo-image-wrap image{
width: 190rpx;
height: 190rpx;
}
.photo-image-wrap text{
font-size: 17px;
color: #000000;
letter-spacing: -0.41px;
}
.photo-image-wrap1{
position: absolute;
left: 120rpx;
bottom: 220rpx;
}
.photo-image-wrap2{
position: absolute;
right: 120rpx;
bottom: 220rpx;
}
.close{
width: 56rpx;
height: 56rpx;
position: absolute;
left: 50%;
margin-left: -28rpx;
bottom: 20rpx;
}
js:
getImage: function () {
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album'],
success: function (res) {
var tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: app.globalData.URL +'/uploadMaterial',
filePath: res.tempFilePaths[0],
name: 'file',
formData: {
'token': app.globalData.token,
},
header: { "Content-Type": "multipart/form-data" },
success: function (result) {
var resultData = JSON.parse(result.data)
console.log(resultData.data.url);
},
fail: function (e) {
console.log(e);
}
})
}
})
},
takePhoto: function () {
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['camera'],
success: function (res) {
var tempFilePaths = res.tempFilePaths
}
})
},