從微信小程序中返回的用戶頭像臨時地址 http://tmp/H0GP7BW5HTQs846c0d9deef32d42f2203340efc4a5c3.jpeg 會失效,且只能一段時間內(nèi)在微信訪問,并且無法在公網(wǎng)訪問用戶頭像臨時地址avatarUrl。
所以需要將臨時地址avatarUrl轉(zhuǎn)成實(shí)際可用的地址保存到mysql數(shù)據(jù)庫的wxusers表的avatarUrl列中,同時將新的圖片路徑保存到服務(wù)器的./public/upload目錄下。
一開始我是這么寫的:
微信小程序通過授權(quán)獲取用戶頭像的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>
對應(yīng)的微信小程序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)
? ? ? ? ? ? ?// 發(fā)送 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("成功獲取到用戶頭像存入數(shù)據(jù)庫:",avatarUrl)
? ? },
? ? fail: function(res) {
? ? ? ? console.log('submit fail');
? ? }
})
}
})
}else{
console.log('wx.login()調(diào)用失??!'+res.errMsg);
}
}
})
},
以nodejs為后臺保存頭像到mysql數(shù)據(jù)庫的路由代碼如下
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;
? ? // 創(chuàng)建MySQL查詢
? ? const sqlStr = 'SELECT * FROM wxusers WHERE openid = ?';
? ? //res.json({openid: openid});
? ? console.log(`查詢到了`)
? ? // 查詢數(shù)據(jù)庫
? ? 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;
接下來是第二次修改的,微信開發(fā)者工具在本地測試沒有問題:
微信小程序通過授權(quán)獲取用戶頭像的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>
對應(yīng)的微信小程序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("成功獲取到用戶頭像存入數(shù)據(jù)庫:", data.path);
? ? },
? ? fail(res) {
? ? console.log('upload fail');
? ? }
? ? })
? ? }
? ? }
? ? })
? ? },
以nodejs為后臺保存頭像到mysql數(shù)據(jù)庫的路由代碼如下:
const express = require('express');
const router = express.Router();
const sql = require('../sql');
const multer = require('multer');
// 設(shè)置文件上傳的目錄
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;
// 創(chuàng)建MySQL查詢
? ? const sqlStr = 'SELECT * FROM wxusers WHERE openid = ?';
// 查詢數(shù)據(jù)庫
? ? 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;
本地運(yùn)行后微信開發(fā)者顯示下面的內(nèi)容:
?然后將服務(wù)搬到服務(wù)器上運(yùn)行之后,開始報(bào)錯:
文章來源:http://www.zghlxwxcb.cn/news/detail-621329.html
?目前解決辦法我也已經(jīng)找到了:點(diǎn)擊閱讀完美解決方案http://t.csdn.cn/nI1pI文章來源地址http://www.zghlxwxcb.cn/news/detail-621329.html
到了這里,關(guān)于微信小程序上傳頭像的臨時路徑,持久化保存到服務(wù)器與數(shù)據(jù)庫(nodejs后臺開發(fā))的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!