在小程序中,经常需要上传本地(手机)上的文件到服务端,最场景的是上传照片。本文演示如何使用微信小程序中提供的上传文件的功能。
修改 xwml 文件
修改 xwml 文件,增加一个按钮触发图片的选取和上传,再添加一个 image 控件用于显示选中的图片。 代码如下:
1 2 3 4 5 6
| <view> <button bindtap="upload">上传图片</button> </view> <view> <image src="{{ img }}" /> </view>
|
修改 js 文件
修改对应页面的 js 文件,添加 upload 函数的实现,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| upload: function() { var that = this wx.chooseImage({ count: 1, sizeType: ['origina', 'compressed'], sourceType: ['album', 'camera'], success: function(res) { that.setData({ img: res.tempFilePaths }) var tempFilePaths = res.tempFilePaths wx.uploadFile({ filePath: tempFilePaths[0], name: 'file', url: 'http://localhost:5000/api/v1/product/check/photo',
success: function(res) { console.log(res.data) }, fail: function(e) { console.log('fail to upload file: ' + JSON.stringify(e)) } }) } })
|
这里,先用本地的服务接口来进行调试,所以在 URL 中使用了 localhost 作为服务的主机。