微信小程序实现带参数的base64图片上传
时间: 2023-10-08 16:10:09 浏览: 110
微信小程序可以通过wx.request方法实现图片上传,而带参数的base64图片上传需要先将base64编码转换为文件流并附加参数,然后再发送请求上传。以下是实现过程的示例代码:
1. 将base64编码转换为文件流
```
// 将base64编码转换为文件流
function base64ToFile(base64Data, fileName) {
const array = wx.base64ToArrayBuffer(base64Data)
const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`
wx.getFileSystemManager().writeFile({
filePath,
data: array,
encoding: 'binary',
success: () => {
console.log('base64转文件流成功')
return filePath
},
fail: () => {
console.log('base64转文件流失败')
return null
}
})
}
```
2. 将文件流和参数一起上传
```
// 上传图片
function uploadImage(filePath, params) {
const token = wx.getStorageSync('token')
const header = {
'Authorization': `Bearer ${token}`,
'content-type': 'multipart/form-data'
}
wx.uploadFile({
url: 'https://example.com/upload',
filePath: filePath,
name: 'file',
formData: params,
header: header,
success: (res) => {
console.log('上传成功', res)
},
fail: (res) => {
console.log('上传失败', res)
}
})
}
```
3. 调用函数进行上传
```
const base64Data = 'data:image/png;base64,iVBORw0KGg...';
const fileName = 'image.png';
const params = {param1: 'value1', param2: 'value2'};
const filePath = base64ToFile(base64Data, fileName);
uploadImage(filePath, params);
```
注意:上传文件需要在开发者工具中设置“不校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书”选项。在真机上测试时,需要在小程序管理后台的“开发设置”中添加上传图片的域名。
阅读全文
相关推荐


















