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

先展示一下完整的项目目录,其实也是非常简单的。就一个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文件夹就会保存对应的文件了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Node.js是一个基于Chrome V8引擎的JavaScript运行环境,它可以使JavaScript在服务器端运行。要实现文件上传和下载,可以使用Node.js的一些模块和框架来简化开发过程。 对于文件上传,可以使用Multer作为中间件进行数据处理。Multer是一个流行的Node.js中间件,用于处理表单数据,特别是文件上传。以下是一个简单的示例代码: ```javascript const express = require('express'); const multer = require('multer'); const app = express(); const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.single('file'), (req, res) => { // 处理上传的文件 console.log(req.file); res.send('文件上传成功!'); }); app.listen(8080, () => { console.log('服务器已启动,监听端口8080'); }); ``` 上述代码创建了一个基本的Express应用程序,并使用Multer中间件来处理文件上传。`upload.single('file')`表示只接受名为`file`的单个文件。在回调函数中可以进行文件处理的操作。 对于文件下载,可以使用Node.js的内置模块`fs`和`http`来实现。以下是一个简单的示例代码: ```javascript const http = require('http'); const fs = require('fs'); http.createServer((req, res) => { if (req.method === 'GET' && req.url === '/download') { const file = fs.createReadStream('path/to/file.txt'); res.setHeader('Content-disposition', 'attachment; filename=file.txt'); file.pipe(res); } }).listen(8080, () => { console.log('服务器已启动,监听端口8080'); }); ``` 上述代码创建了一个简单的HTTP服务器,当GET请求路径为`/download`时,会将文件作为附件下载。可以通过设置`Content-disposition`头来指定下载文件的名称。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值