21xrx.com
2025-04-17 04:10:54 Thursday
文章检索 我的文章 写文章
Node.js实现文件上传至指定目录
2023-07-01 11:01:37 深夜i     18     0
Node js 文件上传 指定目录

在现代Web应用程序中,文件上传已经成为必备功能之一。而Node.js作为一种高效、轻量级的服务器端语言,也提供了方便的文件上传功能。本文将介绍如何使用Node.js将文件上传到指定目录。

## 1. 安装`formidable`模块

`formidable`是一个用于处理文件上传的Node.js模块,可以很方便地解析上传的文件,并提供相关信息。为了使用`formidable`模块,首先需要进行安装。可以在命令行中使用以下命令进行安装:

npm install formidable

## 2. 编写服务器端代码

在服务器端,需要通过Node.js代码来处理文件上传请求。下面是一个简单的Node.js服务器端代码,用于将上传的文件保存到指定目录中:

const http = require('http');
const formidable = require('formidable');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
 if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
  const form = new formidable.IncomingForm();
  form.uploadDir = path.join(__dirname, 'uploads');
  form.parse(req, (err, fields, files) => {
   if (err) {
    console.error(err);
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Internal server error');
    return;
   }
   const oldPath = files.file.path;
   const newPath = path.join(form.uploadDir, files.file.name);
   fs.rename(oldPath, newPath, err => {
    if (err) {
     console.error(err);
     res.writeHead(500, { 'Content-Type': 'text/plain' });
     res.end('Internal server error');
     return;
    }
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('File uploaded successfully');
   });
  });
 } else {
  res.writeHead(404, { 'Content-Type': 'text/plain' });
  res.end('Not found');
 }
});
server.listen(3000, () => {
 console.log('Server is running on http://localhost:3000');
});

这段代码首先创建了一个Node.js服务器,并监听端口`3000`。当收到`/upload`的POST请求时,将会使用`formidable`模块解析上传的表单数据。`formidable`会自动将上传的文件保存到一个临时目录中,并返回相关信息。接下来,将文件从临时目录中移动到指定目录中。最后,服务器会返回一个表示上传成功的响应。

## 3. 编写客户端代码

在客户端,需要通过HTML表单来上传文件,并将其发送到服务器。下面是一个简单的HTML表单,用于上传文件:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Upload file</title>
 </head>
 <body>
  <form action="http://localhost:3000/upload" method="post" enctype="multipart/form-data">
   <input type="file" name="file">
   <button type="submit">Upload</button>
  </form>
 </body>
</html>

这段HTML代码创建了一个包含单个文件上传的表单。当表单被提交时,它会将文件发送到服务器端的`/upload`地址。

## 4. 运行服务器

最后,可以使用命令行启动Node.js服务器,并打开客户端HTML页面进行文件上传。运行以下命令:

node server.js

在浏览器中打开`http://localhost:3000`,选择一个文件并上传。服务器会将文件保存到`uploads`目录中。

## 结论

通过使用Node.js和`formidable`模块,我们可以很容易地将文件上传到服务器的指定目录。此外,Node.js还提供了许多其他有用的功能,如网络编程、数据库连接等等,使得它成为一种非常强大的服务器端编程语言。

  
  

评论区