node.js文件上传重命名以及移动位置的示例代码

yizhihongxing

下面我会给出一个使用Node.js实现文件上传、重命名以及移动位置的示例代码,并讲解具体步骤。

环境准备

在开始之前,我们需要确保计算机上已经安装了Node.js。同时需要安装以下两个Node.js模块:

  • formidable:用于处理文件上传;
  • fs:用于处理文件操作。

可以通过以下命令进行安装:

npm install formidable fs

文件上传

下面来看具体的代码。首先我们需要创建一个Node.js脚本文件,例如 upload.js,并导入 formidablehttp 模块:

const http = require('http');
const formidable = require('formidable');

然后,我们创建一个服务器,并监听一个POST请求,处理文件上传:

http.createServer((req, res) => {  
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = formidable({ multiples: true });

    form.parse(req, (err, fields, files) => {
      if (err) {
        console.error(err);
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('Error occurred while uploading file.');
        return;
      }

      // 文件上传成功
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('File uploaded successfully.');
    });
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Invalid request');
  }
})

在上述代码中,我们使用了 formidable 模块的 form.parse() 方法解析请求。该方法将会把上传的文件信息解析后储存在 files 参数中。

文件重命名以及移动

文件上传成功后,我们可以在上传文件时进行文件重命名,并移动文件到特定位置。我们可以使用 fs 模块的 fs.rename() 方法来完成这一操作。

下面是完整的代码:

const http = require('http');
const formidable = require('formidable');
const fs = require('fs');

http.createServer((req, res) => {  
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = formidable({ multiples: true });

    form.parse(req, (err, fields, files) => {
      if (err) {
        console.error(err);
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('Error occurred while uploading file.');
        return;
      }

      const uploadedFile = files.uploadFile;

      // 重命名文件
      const fileNewName = Date.now() + '_' + uploadedFile.name;
      const fileNewPath = __dirname + '/uploads/' + fileNewName;
      fs.rename(uploadedFile.path, fileNewPath, (err) => {
        if (err) {
          console.error(err);
          res.writeHead(500, { 'Content-Type': 'text/plain' });
          res.end('Error occurred while renaming file.');
          return;
        }

        console.log(`File ${uploadedFile.name} uploaded and renamed to ${fileNewName}`);
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('File uploaded successfully and renamed.');
      });
    });
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Invalid request');
  }
}).listen(3000, () => {
  console.log('Server started on port 3000');
});

在上述代码中,我们先使用 uploadedFile.name 应用了一个新文件名。然后我们使用 __dirname 获取当前脚本所在目录,并使用 /uploads/ 拼接出新的文件路径,最后使用 fs.rename() 方法完成文件的重命名和移动。

示例说明

下面是两个示例,演示如何从本地上传文件,并在文件上传时对文件进行重命名、移动,并将上传成功的信息显示在网页上。

示例1

在示例1中,我们将在上传成功后把文件重命名为上传用户名+时间,并存储在 ./uploads/ 文件夹中。

在文件上传后,在浏览器中输入 http://localhost:3000 即可打开页面进行文件上传。

const http = require('http');
const formidable = require('formidable');
const fs = require('fs');

http.createServer((req, res) => {  
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = formidable({ multiples: true });

    form.parse(req, (err, fields, files) => {
      if (err) {
        console.error(err);
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('Error occurred while uploading file.');
        return;
      }

      const uploadedFile = files.uploadFile;

      // 获取上传用户名和文件后缀
      const username = fields.username;
      const fileExt = uploadedFile.name.split('.').pop();

      // 重命名文件
      const fileNewName = username + '_' + Date.now() + '.' + fileExt;
      const fileNewPath = __dirname + '/uploads/' + fileNewName;
      fs.rename(uploadedFile.path, fileNewPath, (err) => {
        if (err) {
          console.error(err);
          res.writeHead(500, { 'Content-Type': 'text/plain' });
          res.end('Error occurred while renaming file.');
          return;
        }

        console.log(`File ${uploadedFile.name} uploaded and renamed to ${fileNewName}`);
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('File uploaded successfully and renamed.');
      });
    });
  } else {
    const html = `
      <html>
        <head>
          <meta charset="utf-8">
          <title>文件上传</title>
        </head>
        <body>
          <h3>文件上传</h3>
          <form action="/upload" method="post" enctype="multipart/form-data">
            <input type="text" name="username" placeholder="请输入用户名"><br>
            <input type="file" name="uploadFile" multiple="multiple"><br>
            <input type="submit" value="提交">
          </form>
        </body>
      </html>
    `;
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(html);
  }
}).listen(3000, () => {
  console.log('Server started on port 3000');
});

示例2

在示例2中,我们将在上传成功后把文件重命名为时间戳,并存储在 ./uploads/ 文件夹中。上传成功后,将会在页面上显示上传成功信息和上传文件预览链接。

在文件上传后,在浏览器中输入 http://localhost:3000 即可打开页面进行文件上传。

const http = require('http');
const formidable = require('formidable');
const fs = require('fs');

http.createServer((req, res) => {  
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = formidable({ multiples: true });

    form.parse(req, (err, fields, files) => {
      if (err) {
        console.error(err);
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('Error occurred while uploading file.');
        return;
      }

      const uploadedFile = files.uploadFile;

      // 重命名文件
      const fileNewName = Date.now() + '_' + uploadedFile.name;
      const fileNewPath = __dirname + '/uploads/' + fileNewName;
      fs.rename(uploadedFile.path, fileNewPath, (err) => {
        if (err) {
          console.error(err);
          res.writeHead(500, { 'Content-Type': 'text/plain' });
          res.end('Error occurred while renaming file.');
          return;
        }

        console.log(`File ${uploadedFile.name} uploaded and renamed to ${fileNewName}`);
        const html = `
          <html>
            <head>
              <meta charset="utf-8">
              <title>文件上传结果</title>
            </head>
            <body>
              <h3>文件上传成功</h3>
              <div>
                <p>文件名:<a href="./uploads/${fileNewName}" target="_blank">${fileNewName}</a></p>
                <p>文件大小:${uploadedFile.size}</p>
                <p>文件类型:${uploadedFile.type}</p>
                <p>预览链接:<a href="./uploads/${fileNewName}" target="_blank">${uploadedFile.name}</a></p>
              </div>
            </body>
          </html>
        `;
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(html);
      });
    });
  } else {
    const html = `
      <html>
        <head>
          <meta charset="utf-8">
          <title>文件上传</title>
        </head>
        <body>
          <h3>文件上传</h3>
          <form action="/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="uploadFile" multiple="multiple"><br>
            <input type="submit" value="提交">
          </form>
        </body>
      </html>
    `;
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(html);
  }
}).listen(3000, () => {
  console.log('Server started on port 3000');
});

以上就是使用Node.js实现文件上传、重命名以及移动位置的完整攻略,希望能对你有所帮助。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:node.js文件上传重命名以及移动位置的示例代码 - Python技术站

(0)
上一篇 2023年6月8日
下一篇 2023年6月8日

相关文章

  • Nodejs高扩展性的模板引擎 functmpl简介

    Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时,是一个使用非阻塞和事件驱动 I/O模型的服务器端 JavaScript 环境。但是Node.js 自身并不具备模板引擎功能,于是出现了大量的第三方模板引擎,其中 functmpl 就是一款高扩展性的模板引擎。 什么是 functmpl functmpl 是一个轻量级的 Ja…

    node js 2023年6月8日
    00
  • Nodejs进阶:基于express+multer的文件上传实例

    下面我将介绍一下“Nodejs进阶:基于express+multer的文件上传实例”的完整攻略。 简介 在Web应用程序开发中,文件上传是一个非常常见的需求。Node.js 提供了强大的文件系统模块,可以轻松读取和写入文件。而 Express 框架则提供了处理 HTTP 请求和响应的能力。 Multer 是一款 Node.js 中用于处理 multipart…

    node js 2023年6月8日
    00
  • JavaScript数据结构与算法之二叉树实现查找最小值、最大值、给定值算法示例

    JavaScript数据结构与算法之二叉树实现查找最小值、最大值、给定值算法示例 二叉树简介 二叉树是一种非常重要的数据结构,它可以给我们提供高效的算法实现,如查找、插入、删除等。二叉树是由节点(node)构成的,每个节点最多只有两个子节点。在 JavaScript 中,我们可以用对象的形式来表示一个二叉树节点,如下: class Node { constr…

    node js 2023年6月8日
    00
  • JS调用某段SQL语句的方法

    在Javascript中调用SQL语句的方法需要借助数据库中间件或是直接调用浏览器提供的IndexedDB API进行操作。 使用数据库中间件 数据库中间件如Firefox的sql.js,可以让JavaScript直接操作SQLite数据库。可以类似于如下方式调用: const SQL = require(‘sql.js’); const fs = requ…

    node js 2023年6月8日
    00
  • JavaScript 中如何拦截全局 Fetch API 的请求和响应问题

    对于拦截全局 Fetch API 的请求和响应问题,我们可以使用 window.fetch 方法的第二个参数 init 来进行拦截。init 是一个配置对象,包含了 HTTP 请求的相关配置,其中,我们可以设置 init 中的 headers 属性来拦截请求和响应。 拦截 Fetch 请求 为了拦截 Fetch 请求,我们可以在 headers 中添加 fe…

    node js 2023年6月8日
    00
  • 详解如何修改 node_modules 里的文件

    要修改 node_modules 目录下的文件,有以下几种方式可以实现。 1. 直接在 node_modules 目录下修改文件 这是最简单最直接的方式,但不推荐使用。因为这种方式可能会导致在项目更新或重新安装依赖时出现一些问题,因为这些修改都不会被记录到 package.json 中。 2. 使用 npm 或 yarn 的 patch 命令 这种方式是一个…

    node js 2023年6月8日
    00
  • 使用Node.js实现Clean Architecture方法示例详解

    下面就来讲解“使用Node.js实现Clean Architecture方法示例详解”的完整攻略。 Clean Architecture概述 Clean Architecture是一种软件设计理念,其核心思想是将业务逻辑和技术细节分离,让软件更加灵活和易于维护。Clean Architecture包含以下几个核心组件: 实体(Entity) 用例(Use C…

    node js 2023年6月8日
    00
  • 如何在CocosCreator中利用常驻节点做图层管理

    如何在CocosCreator中利用常驻节点做图层管理? 一、常驻节点 在CocosCreator中,可以通过创建常驻节点来管理所有节点。常驻节点一般用于保存全局数据或者场景切换时需要持续存在的数据。 创建常驻节点: 1.在层级管理器中右键选择”Create”,选择”Node”,创建一个普通节点。 2.将该节点拖拽到”Canvas”上使其成为Canvas的子…

    node js 2023年6月8日
    00
合作推广
合作推广
分享本页
返回顶部