微信小程序实现上传图片至页面显示的功能 
时间: 2023-05-27 09:01:16 浏览: 38
1. 在wxml文件中添加一个图片预览框:
```html
<view class="image-preview">
<image src="{{imageSrc}}" mode="aspectFill"></image>
</view>
```
2. 在js文件中获取图片并上传:
```javascript
Page({
// 选择图片
chooseImage: function () {
var that = this;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
that.setData({
imageSrc: tempFilePaths[0],
})
// 上传图片
wx.uploadFile({
url: 'http://example.com/upload', // 接口地址
filePath: tempFilePaths[0], // 上传文件路径
name: 'file',
header: {
'Content-Type': 'multipart/form-data',
},
success: function (res) {
// 上传成功后,可以在这里更新表单数据
console.log(res.data)
}
})
}
})
},
})
```
3. 在样式表中给图片预览框添加样式:
```css
.image-preview {
margin: 20px;
height: 200px;
}
.image-preview img {
width: 100%;
height: 100%;
}
```
相关推荐


















