Node.js实现图片上传的方法有很多种,下面我将介绍一种常用的方法,使用multer中间件来实现图片上传功能。
步骤1:项目初始化
首先创建一个
express-multer-upload
工程项目,然后使用
npm i express
等命令在项目中下好各种依赖包
mkdir image-upload
cd image-upload
npm init -y
npm install express multer
步骤2:创建一个index.js
文件并编写以下代码:
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
// 设置存储引擎
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
// 初始化multer
const upload = multer({ storage: storage })
// 设置静态文件目录
app.use(express.static('public'));
// 上传页面
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// 处理上传
app.post('/upload', upload.single('image'), (req, res) => {
res.send('文件上传成功');
});
// 启动服务器
app.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
步骤3:创建一个index.html
文件来创建一个简单的上传表单:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片上传</title>
</head>
<body>
<h1>上传图片</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<button type="submit">上传</button>
</form>
</body>
</html>