The temporary path for uploading avatars to WeChat applet and persisting them to the server and database (nodejs background development)

The temporary address of the user's avatar, http://tmp/H0GP7BW5HTQs846c0d9deef32d42f2203340efc4a5c3.jpeg, returned from the WeChat applet will become invalid and can only be accessed within a period of time on WeChat, and the temporary address of the user's avatar, avatarUrl, cannot be accessed on the public network.

Therefore, it is necessary to convert the temporary address avatarUrl into an actually usable address and save it in the avatarUrl column of the wxusers table in the mysql database, and at the same time save the new image path to the ./public/upload directory of the server.

At first I wrote this:

The wxml code for WeChat applet to obtain user avatar through authorization is as follows

<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>


The corresponding WeChat applet TS code is as follows

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);
}
}
})
},


The routing code for saving avatars to mysql database using nodejs as the background is as follows

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;

Next is the second modification. The WeChat developer tool has no problem in local testing:

The wxml code for the WeChat applet to obtain the user's avatar through authorization is as follows:

    <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>


The corresponding WeChat applet TS code is as follows:

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');
    }
    })
    }
    }
    })
    },


The routing code for saving avatars to mysql database using nodejs as the background is as follows:

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;

After running locally, the WeChat developer displays the following content:

 Then after moving the service to the server and running it, errors started to appear:

 I have also found the current solution: click to read the perfect solution icon-default.png?t=N6B9http://t.csdn.cn/nI1pI

Guess you like

Origin blog.csdn.net/qq_25501981/article/details/131493971