微信小程序上传头像的临时路径,持久化保存到服务器与数据库(nodejs后台开发)
·
从微信小程序中返回的用户头像临时地址 http://tmp/H0GP7BW5HTQs846c0d9deef32d42f2203340efc4a5c3.jpeg 会失效,且只能一段时间内在微信访问,并且无法在公网访问用户头像临时地址avatarUrl。
所以需要将临时地址avatarUrl转成实际可用的地址保存到mysql数据库的wxusers表的avatarUrl列中,同时将新的图片路径保存到服务器的./public/upload目录下。
一开始我是这么写的:
微信小程序通过授权获取用户头像的wxml代码如下
<view class="btnavatar">
<button class="avatar-wrapper" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar" value='{{avatarUrl}}'>
<view>
<image class="avatar" src="{{avatarUrl}}"></image>
</view>
</button>
</view>
对应的微信小程序TS代码如下
onChooseAvatar(e) {
const { avatarUrl } = e.detail
this.setData({
avatarUrl,
})
console.log("获取到用户输入的头像为"+ avatarUrl)
// 登录
var that = this;
wx.login({
success: function(res) {
//console.log(res.code)
// 发送 res.code 到后台换取 openId, sessionKey, unionId
if (res.code){
wx.request({
url: config.apiUrl + '/api/getOpenid',
method: 'POST',
data:{
code:res.code,
},
success:function(response){
console.log("成功获取到用户openid 下面开始获取头像:",response.data.openid)
const openid = response.data.openid;
wx.request({
url: config.apiUrl + '/api/avatarUrl',
method: 'POST',
data: {
openid,
avatarUrl,
},
success: function(res) {
console.log('submit success');
console.log("成功获取到用户头像存入数据库:",avatarUrl)
},
fail: function(res) {
console.log('submit fail');
}
})
}
})
}else{
console.log('wx.login()调用失败!'+res.errMsg);
}
}
})
},
以nodejs为后台保存头像到mysql数据库的路由代码如下
const express = require('express');
const router = express.Router();
const sql = require('../sql');
const request = require("request");
//存入头像
router.post('/avatarUrl', (req, res) => {
const openid = req.body.openid;
const avatarUrl = req.body.avatarUrl;
const nickname = req.body.nickname;
const phoneNumber = req.body.phoneNumber;
const unionid = req.body.unionid;
// 创建MySQL查询
const sqlStr = 'SELECT * FROM wxusers WHERE openid = ?';
//res.json({openid: openid});
console.log(`查询到了`)
// 查询数据库
sql.query(sqlStr, [openid], function(err, result) {
if (err) {
console.error(err);
res.status(500).send('Database error');
} else {
// 检查是否有匹配的openId
if (result.length > 0) {
const sqlStr = `UPDATE wxusers SET avatarUrl = '${avatarUrl}' WHERE openid = '${openid}'`;
sql.query(sqlStr, (err, result) => {
if (err) throw err;
res.send('Data updated in the database.');
});
} else {
const sqlStr = `INSERT INTO wxusers (openid, avatarUrl, nickname, phoneNumber, unionid) VALUES ('${openid}','${avatarUrl}', 'default_user', 'default_user', 'default_user')`;
sql.query(sqlStr, [openid, avatarUrl, nickname, phoneNumber, unionid], (err, result) => {
if (err) throw err;
res.send('Data inserted into the database.');
});
}
}
});
});
module.exports = router;
接下来是第二次修改的,微信开发者工具在本地测试没有问题:
微信小程序通过授权获取用户头像的wxml代码如下:
<view data-weui-theme="{{theme}}" class="view-2">
<button class="avatar-wrapper" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar" value='{{avatarUrl}}'>
<view>
<image class="avatar" src="{{avatarUrl}}"></image>
</view>
</button>
对应的微信小程序TS代码如下:
onChooseAvatar(e) {
const { avatarUrl } = e.detail
this.setData({
avatarUrl,
})
console.log("获取到用户头像avatarUrl:"+ avatarUrl)
// 下载头像图片
wx.downloadFile({
url: avatarUrl,
success(res) {
if (res.statusCode === 200) {
console.log('download success');
const tempFilePath = res.tempFilePath
console.log("获取到用户头像tempFilePath:"+ tempFilePath)
// 上传下载的图片
wx.uploadFile({
url: config.apiUrl + '/api/avatarUrl',
filePath: tempFilePath,
name: 'file',
formData: {
'openid': wx.getStorageSync('openid')
},
success(res) {
const data = JSON.parse(res.data)
console.log('upload success');
console.log("成功获取到用户头像存入数据库:", data.path);
},
fail(res) {
console.log('upload fail');
}
})
}
}
})
},
以nodejs为后台保存头像到mysql数据库的路由代码如下:
const express = require('express');
const router = express.Router();
const sql = require('../sql');
const multer = require('multer');
// 设置文件上传的目录
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './public/upload')
},
filename: function(req, file, cb) {
cb(null, Date.now() + '-' + file.originalname)
}
})
const upload = multer({ storage: storage })
router.post('/avatarUrl', upload.single('file'), (req, res) => {
const openid = req.body.openid;
const avatarUrl = '/upload/' + req.file.filename;
// 创建MySQL查询
const sqlStr = 'SELECT * FROM wxusers WHERE openid = ?';
// 查询数据库
sql.query(sqlStr, [openid], function(err, result) {
if (err) {
console.error(err);
res.status(500).send('Database error');
} else {
// 检查是否有匹配的openId
if (result.length > 0) {
const sqlStr = `UPDATE wxusers SET avatarUrl = '${avatarUrl}' WHERE openid = '${openid}'`;
sql.query(sqlStr, (err, result) => {
if (err) throw err;
res.json({ path: avatarUrl });
});
console.log("更新新路径", avatarUrl);
} else {
const sqlStr = `INSERT INTO wxusers (openid, avatarUrl) VALUES ('${openid}','${avatarUrl}')`;
sql.query(sqlStr, [openid, avatarUrl], (err, result) => {
if (err) throw err;
res.json({ path: avatarUrl });
});
console.log("插入新路径", avatarUrl);
}
}
});
});
module.exports = router;
本地运行后微信开发者显示下面的内容:
然后将服务搬到服务器上运行之后,开始报错:
目前解决办法我也已经找到了:点击阅读完美解决方案http://t.csdn.cn/nI1pI
更多推荐
已为社区贡献1条内容
所有评论(0)