[node] Use express+gitee to build a picture bed and solve the problem of anti-leech

First create a gitee project, I will not explain the detailed steps one by one

Note: Please remember to open source this project, and remember to obtain your own private key. The operation of the private key is as follows:

Node depends on downloading:

    "axios":     "cors":     "express":     "multer":     "nodemon":

app.js code:

const express = require('express');
const multer = require('multer');
const axios = require('axios');
const cors = require('cors');

const app = express();
app.use(cors());
const port = 3000;

// 设置 Multer 中间件来处理文件上传
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

// 处理静态文件
app.use(express.static('public'));

// 显示图床上的所有图片
app.get('/', async (req, res) => {
  try {
    const response = await axios.get('https://gitee.com/api/v5/repos/zsd12138/drawing-bed/contents/image?access_token=xxxxxxxxxx');
    const images = response.data.map(item => item.download_url);
    res.send(`
      <div style="display: flex;">
        ${images.map(image =>
      `<div style="display: flex;
          flex-direction: column;
          align-items: center;"><img src="${image}" style="height: 200px;margin-right: 20px;"> <span  style="cursor: pointer;">点击图片删除</span></div>`
    ).join('')}
      </div>
    `);
  } catch (error) {
    console.error(error);
    res.status(500).send('无法获取图片列表');
  }
});

// 上传图片到图床
app.post('/upload', upload.single('image'), async (req, res) => {
  try {
    const { buffer, originalname } = req.file;
    const encodedFile = buffer.toString('base64');
    const response = await axios.post('https://gitee.com/api/v5/repos/zsd12138/drawing-bed/contents/image/' + originalname, {
      access_token: "xxxxxxxxxx",
      branch: 'master',
      content: encodedFile,
      message: `上传图片 ${originalname}`,
    });
    res.status(200).send(response.data);
  } catch (error) {
    // console.error(error);
    res.status(500).send('无法上传图片');
  }
});

// 删除图床上的图片
app.get('/delete/:filename', async (req, res) => {
  const filename = req.params.filename;
  try {
    // 获取sha
    const shaDate = await axios.get('https://gitee.com/api/v5/repos/zsd12138/drawing-bed/contents/image/' + filename + '?access_token=xxxxxxxxxxx');
    // console.log(shaDate.data.sha)
    // 删除操作
    const response = await axios.delete('https://gitee.com/api/v5/repos/zsd12138/drawing-bed/contents/image/' + filename, {
      params: {
        access_token: "xxxxxxxxxxxxx",
        branch: 'master',
        message: `删除图片 ${filename}`,
        sha: shaDate.data.sha
      },
    });
    res.status(200).send(`已删除${filename}`);
  } catch (error) {
    console.error(error.data);
    res.status(500).send(`无法删除图片 ${filename}`);
  }
});

// 启动服务器
app.listen(port, () => {
  console.log(`服务器正在运行,访问 http://localhost:${port}`);
});

access_token replaced with your own private token

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>图床</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
    <h2>上传图片</h2>
    <form id="uploadForm">
        <input type="file" id="fileInput">
        <button type="submit">上传图片</button>
    </form>

    <h2>所有图片</h2>
    <div id="images"></div>

    <script>
        $(function () {
            // 删除图片
            $('#images').on('click', 'img', function () {
                const imageUrl = $(this).attr('src');
                const filename = imageUrl.substring(imageUrl.lastIndexOf('/') + 1);
                if (confirm(`确定删除 "${filename}"?`)) {
                    $.ajax({
                        url: 'http://172.21.2.52:3000/delete/' + filename,
                        type: 'get',
                        success: () => {
                            // $(this) 表示当前被选中的元素,.remove() 用于从 DOM 中移除元素。
                            // $(this).remove();
                            getIamge()
                        },
                        error: () => {
                            alert('Delete failed.');
                        }
                    });
                }
            });
        })
        var getIamge = function () {
            // 获取图床上的所有图片
            $.ajax({
                url: 'http://172.21.2.52:3000/',
                method: 'GET',
                success: function (html) {
                    $('#images').html(html);
                },
                error: function () {
                    console.error('无法获取图片列表');
                }
            });
        }
        getIamge()
        // 上传图片到图床
        $('#uploadForm').submit(function (event) {
            event.preventDefault(); // 阻止表单的默认提交行为

            const formData = new FormData();
            formData.append('image', $('#fileInput')[0].files[0]);
            console.log($('#fileInput')[0].files[0])
            $.ajax({
                url: 'http://172.21.2.52:3000/upload',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (result) {
                    getIamge()
                    console.log(result);
                },
                error: function (error) {
                    console.error(error);
                }
            });
        })

    </script>
</body>

</html>

Running effect: all are 302 redirected, this is the anti-leech link, let’s talk about anti-leech link

Anti-leech

To implement anti-leeching, you need to know where the request for the image is sent from. originThis function can be achieved with the sum in the request header referer. originIt will only be brought in the XHR request, so image resources can only be usedreferer

By judging the referer of the request, if the source of the request is not from this site, return 302

A complete process:

  • First request a normal picture, but instead of returning 200, it is 302 redirected, where the location in the response header is the address to be redirected to;
  • Then the browser will automatically request this location, and use this returned result to replace the returned content of the first request

How to crack anti-leech

If you want gitee not to know that I am stealing, you can't let him find out that the source of the request is a third party, just hide the referer

Code:

//增加到html的头部
<meta name="referrer" content="no-referrer" />

Note:
<meta name="referrer" content="no-referrer" />Specifying "no-referrer" means that the browser will not include any referrer information when sending the request. In other words, when the user jumps from the current web page to another page, the request received by the new page will not contain the address of the page before the jump

Final rendering

After adding the meta header configuration 

Attach the gitee request document:

Gitee API Documentation

Guess you like

Origin blog.csdn.net/weixin_52479803/article/details/131774501