nodejs实现文件上传保存在本地

文章展示了如何使用Node.js的Express框架和Multer库创建一个简单的文件上传服务。首先创建一个HTML表单用于文件选择和提交,然后通过Express设置路由处理POST请求,使用Multer处理上传的文件,将文件存储在uploads目录下。当文件上传成功时,服务器会给出响应。

先展示一下完整的项目目录,其实也是非常简单的。就一个index.js和一个mypage.html
在这里插入图片描述
接下来把完整的代码贴出来
mypage.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="Upload">
    </form>
</body>

</html>

index.js

const express = require('express');
const app = express();
const multer = require('multer');

const fs = require('fs');
const path = require('path');

//读取html代码的部分
const htmlFilePath = path.resolve(__dirname, './html/mypage.html');
const htmlString = fs.readFileSync(htmlFilePath, 'utf8');


// 配置文件上传的服务
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/');
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});
const upload = multer({ storage: storage });

// 定义路由
app.post('/upload', upload.single('file'), function (req, res) {
    const file = req.file;
    console.log("File uploaded successfully!")
    res.end("File uploaded successfully!")
});

app.get('/', (req, res) => {
    res.send(htmlString)
});

// 启动服务器
app.listen(3001, function () {
    console.log('Server is listening on port 3001.');
});

在项目终端运行nom install multer安装multer模块,然后运行node ./index.js
1、首先新建一个文件夹 fileUpload ,在vscode打开,根目录新建一个index.js文件,写入以下代码,启动。启动命令 node ./index.js

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('hello world')
  });
// 启动服务器
app.listen(3001, function () {
    console.log('Server is listening on port 3000.');
  });

如下图所示代表启动成功,浏览器输入http://localhost:3001/就可以访问了
这样就代表启动成功
2、接下来我们就要写一个上传文件的表单了,在根目录新建一个html文件夹,里面建一个mypage.html文件,写入以下代码。这样当我们点击提交的时候就可以把上传的文件提交到 /upload 路由。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="Upload">
    </form>
</body>

</html>

3、将这个html文件用nodejs来读取输出。(大概是这个意思吧),引入fs模块和path模块
index.js修改

const express = require('express');
const app = express();

const fs = require('fs');
const path = require('path');

const htmlFilePath = path.resolve(__dirname, './html/mypage.html');
const htmlString = fs.readFileSync(htmlFilePath, 'utf8');

app.get('/', (req, res) => {
    res.send(htmlString)
});

// 启动服务器
app.listen(3001, function () {
    console.log('Server is listening on port 3001.');
});

浏览器此时出现了上传表单
在这里插入图片描述
4、接下来要用到multer模块,我们先安装一下。在vscode终端运行
npm install multer,然后在项目根目录新建一个文件夹uploads,用来存放上传的文件。
index.js修改后

const express = require('express');
const app = express();
const multer = require('multer');

const fs = require('fs');
const path = require('path');

//读取html代码的部分
const htmlFilePath = path.resolve(__dirname, './html/mypage.html');
const htmlString = fs.readFileSync(htmlFilePath, 'utf8');


// 配置文件上传的服务
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/');
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});
const upload = multer({ storage: storage });

// 定义路由
app.post('/upload', upload.single('file'), function (req, res) {
    const file = req.file;
    console.log("File uploaded successfully!")
    res.end("File uploaded successfully!")
});

app.get('/', (req, res) => {
    res.send(htmlString)
});

// 启动服务器
app.listen(3001, function () {
    console.log('Server is listening on port 3001.');
});

接下来运行项目,在浏览器上传文件后,相应的uploads文件夹就会保存对应的文件了。

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值