小程序云开发如何上存图片
时间: 2023-10-06 16:04:42 浏览: 35
小程序云开发中,可以使用 `wx.cloud.uploadFile()` 方法上传图片。具体步骤如下:
1. 在小程序管理后台开通云开发,并创建一个云开发环境。
2. 在小程序代码中引入云开发 SDK:`const db = wx.cloud.database()`。
3. 在代码中调用 `wx.chooseImage()` 方法选择要上传的图片,并将图片临时文件路径保存到变量中。
4. 调用 `wx.cloud.uploadFile()` 方法上传图片,该方法接收一个对象参数,包括 `cloudPath`、`filePath`、`success` 和 `fail` 四个属性。其中,`cloudPath` 为图片在云存储中的路径,`filePath` 为图片临时文件路径,`success` 和 `fail` 分别是上传成功和失败后的回调函数。
5. 在上传成功的回调函数中,可以获取到图片在云存储中的文件 ID,可以将文件 ID 保存到数据库中,以便后续使用。
示例代码如下:
```javascript
// 选择图片
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
const filePath = res.tempFilePaths[0]
const cloudPath = 'images/' + Date.now() + filePath.match(/\.[^.]+?$/)[0]
// 上传图片
wx.cloud.uploadFile({
cloudPath,
filePath,
success: res => {
const fileId = res.fileID
// 将 fileId 存入数据库中
db.collection('images').add({
data: {
fileId
}
})
},
fail: console.error
})
}
})
```