之前想着的是使用狼宝来上传博客图片,后来规划了一下,发现这个不是很适合使用直觉,后来问了好多次ChatGpt发现上传图片都需要有一个后端的服务器,然后就接触到了express。在ChatGpt的真实帮助下用express写了一个上传图片的客户端。

Express介绍

Express是一个流行的Node.js Web应用程序框架,它简化了构建Web应用程序和API的过程。它提供了一组简洁而灵活的功能,使得处理HTTP请求、路由、中间件和视图模板等任务变得更加容易。

下面是一些Express框架的主要特点:

  1. 快速而简洁: Express具有简洁的API设计,使得构建Web应用程序变得简单而直观。它提供了一些核心功能,同时也允许开发者根据需求进行扩展。

  2. 路由: Express提供了灵活的路由功能,可以根据URL路径和HTTP方法来处理请求。通过定义路由,您可以将不同的请求映射到相应的处理程序函数,使代码结构清晰且易于维护。

  3. 中间件: Express的中间件是处理HTTP请求的函数。它们可以执行各种任务,例如身份验证、日志记录、错误处理等。中间件函数可以按照顺序串联起来,形成一个处理请求的管道。这种模式使得处理请求的逻辑可以被分解为可重用的组件。

  4. 模板引擎: Express支持各种模板引擎,例如EJS、Pug(以前称为Jade)、Handlebars等。这些模板引擎使得在服务器端生成动态HTML变得容易,可以方便地将数据注入到模板中,生成最终的响应。

  5. 中间件和路由的生态系统: Express有一个庞大的中间件和路由插件生态系统,可以帮助开发者快速集成各种功能,如身份验证、会话管理、数据库连接等。这些插件可以大大提高开发效率,并且经过了广泛的测试和使用。

总的来说,Express是一个轻量级、灵活且易于使用的框架,适用于构建各种类型的Web应用程序和API。它的简单性和丰富的生态系统使得开发者可以更快地构建高性能的Web应用程序,并以可维护的方式组织和扩展代码。

ChatGpt就是人类之光!!!

初始化Express项目

这部分是跟着教程网站的一个引导走的站点

首先你的有nodejs,其次使用 npm install express-generator -g 安装生成器,接着在一个空目录下使用express –view=pug ,然后使用npm install 安装依赖,最后在使用npm run start启动项目。

1
2
3
4
npm install express-generator -g
mkdir express-tutorial && cd express-tutorial
express --view=pug
npm run start

浏览器中导航至 http://localhost:3000/ ,就可以访问该应用。你应该可以看到:
[图片]

目录结构

/express-locallibrary-tutorial
    app.js
    /bin
        www
    package.json
    /node_modules
        [约 4,500 个子文件夹和文件]
    /public
        /images
        /javascripts
        /stylesheets
            style.css
    /routes
        index.js
        users.js
    /views
        error.pug
        index.pug
        layout.pug

开始自定义

修改访问端口和地址

由于整体是在服务器上开发,所有我们测试的时候需要调整端口和开启外网访问。在app.js文件中加入如下的代码:

1
2
3
app.listen(17777,'0.0.0.0', () => {
console.log('Server started on port 17777');
});

添加整体需要的模块/依赖

图片上传的功能需要js-yaml、multer、sharp
js-yaml是用来处理上传文件后将图片信息写到博客对应的配置文件里。
multer是上传文件的主要模块
sharp是图片处理模块,把所有的图片都转化为了webp格式放到指定的位置。

1
npm install js-yaml multer sharp --save

修改router/index.js 添加上传图片的路由和功能

首先还是引入依赖
var sharp = require(‘sharp’);
var multer = require(‘multer’);
var fs = require(‘fs’);
var yaml = require(‘js-yaml’);

设置上载的目录
var uploadDest = multer({dest: ‘./tmp/‘}) // 其实没什么屌用因为我有sharp

新增上载的路由
router.post(‘/upload/:path?’,uploadDest.single(‘image’), function(req, res, next) {});

重命名图片名字并图片格式转化
const filenameNew = new Date().getTime();
sharp(req.file.path)
.webp({ quality: 80 })
.toFile(/root/file/resources/img/${req.params.path}/${filenameNew}.webp, (err, info) => {
if (err) {
console.error(err);
res.status(500).send(‘Internal Server Error’);
} else {
console.log(info);
return res.send(‘Image uploaded and converted to webp’);
}
});

修改博客配置文件
try {
const yamlData = fs.readFileSync(‘/root/code/blog/source/_data/album.yml’, ‘utf8’);
const parsedData = yaml.load(yamlData);
// 查找path_name为/foodPhoto的数据
parsedData.find(item => item.path_name === /${req.params.path}Photo).album_list[0].image.push(https://resources.kagerou.top/img/${req.params.path}{filenameNew}.webp);
const updatedYamlData = yaml.dump(parsedData);
fs.writeFileSync(‘/root/code/blog/source/_data/album.yml’, updatedYamlData, ‘utf8’);
//更新blog
return res.send(‘seccess’);
}catch (err) {
console.error(‘无法读取YAML文件:’, err);
}

整体index.js代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
var express = require('express');
var sharp = require('sharp');
var multer = require('multer');
var fs = require('fs');
var yaml = require('js-yaml');

var router = express.Router();

var uploadDest = multer({dest: './tmp/'})

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});

/*upload single file */
router.post('/upload/:path?',uploadDest.single('image'), function(req, res, next) {
const filenameNew = new Date().getTime();
sharp(req.file.path)
.webp({ quality: 80 })
.toFile(`/root/file/resources/img/${req.params.path}/${filenameNew}.webp`, (err, info) => {
if (err) {
console.error(err);
res.status(500).send('Internal Server Error');
} else {
console.log(info);
//修改blog中的album.yml
try {
const yamlData = fs.readFileSync('/root/code/blog/source/_data/album.yml', 'utf8');
const parsedData = yaml.load(yamlData);
// 查找path_name为/foodPhoto的数据
parsedData.find(item => item.path_name === `/${req.params.path}Photo`).album_list[0].image.push(`https://resources.kagerou.top/img/${req.params.path}/${filenameNew}.webp`);
const updatedYamlData = yaml.dump(parsedData);
fs.writeFileSync('/root/code/blog/source/_data/album.yml', updatedYamlData, 'utf8');
return res.send('Image uploaded and converted to webp');
}catch (err) {
console.error('无法读取YAML文件:', err);
}
return res.send('Image uploaded and converted to webp');
}
});
});

module.exports = router;

多图片上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
router.post('/uploads/:path?',uploadDest.array('images',9), function(req, res, next) {
req.files.forEach(file => {
const filenameNew = new Date().getTime();
sharp(file.path)
.webp({ quality: 80 })
.toFile(`/usr/qibao/upload/${req.params.path}/${filenameNew}.webp`, (err, info) => {
if (err) {
console.error(err);
res.status(500).send('Internal Server Error');
} else {
console.log(info);
res.send('Images uploaded and converted to webp');
}
});
});
});

启动express

使用npm run start启动就好了

上传页面(还在新建文件夹)