node.js之文件上传功能

本文介绍如何使用Node.js实现文件上传功能,包括设置web服务、安装和配置multiparty包、处理上传请求及重命名文件等步骤。


步骤:

1、完成通过form表单发送普通的POST请求
    1.1、开启web服务,让浏览器访问的时候,给它返回一个form表单的页面
    
    1.2、后台进行处理

2、完成通过form表单发送文件上传的POST请求
    1.1、在项目根目录生成一个package.json的文件,它有一个作用,就是记录我们安装过哪些第三方包
        切换到项目根目录,但是项目名称不能是中文,执行 npm init -y
        
    1.2、安装 multiparty 这个第三方包
        切换到项目根目录,使用 npm i multiparty -S/--save
        
    1.3、根据第三方包的文档,写代码(拷贝代码)
        
    1.4、对我们上传的文件名称进行重新命名
        我们约定,我们的文件名称就命令成年月日时分秒毫秒
        
        安装 date-format  npm i date-format -S


// 1. 导入http模块
const http = require('http')
const fs = require('fs')
const path = require('path')
const querystring = require('querystring')
const util = require('util')
const multiparty = require('multiparty')
const format = require('date-format');
// 2. 创建server
http
    .createServer(function(req,res) {
      if (req.url.includes('index')) {
        const filePath = path.join(__dirname,'index.html')

        const htmlBuffer = fs.readFileSync(filePath)
        res.setHeader('Content-Type','text/html;charset=utf-8')
        res.end(htmlBuffer)
      }else if(req.url.includes('upload')) {
        // 对上传过来的请求数据,进行处理,会创建文件夹
        const dirPath = path.join(__dirname,'upload')
        const exists = fs.existsSync(dirPath)
        if(!exists) {
          const err = fs.mkdirSync(dirPath)
          if (err) {
            console.log(err)
          }
          console.log('mkdir OK')
        }

        // 创建form表单对象
        var form = new multiparty.Form({
          uploadDir:dirPath   将文件存在文件夹里面
        })

        form.parse(req, function(err, fields, files) {
          console.log(fields);
          Object.keys(fields).forEach(function(name) {
            console.log(`${name} is ${fields[name][0]}`);
          });
         
          Object.keys(files).forEach(function(name) {
            console.log(name);
            const file=files[name][0]
            const oldPath=file.path;
            const newPath=path.join(__dirname,'upload',`${format('yyyyMMddhhmmssSSS',new Date())}.txt`)
            const err=fs.renameSync(oldPath,newPath)
            if(err){
              console.log(err);
            }
            console.log('rename ok');
          });
          res.writeHead(200, {'content-type': 'text/plain'});
          res.write('received upload:\n\n');
          res.end(util.inspect({fields: fields, files: files}));
        })


      }
    })
    .listen(80,function() {
      console.log('running...')
    })

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
     
    </style>
</head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="text" name="username">
        <input type="password" name="password">
        <input type="file" name="file1">
        <input type="file" name="file2">
        <input type="submit" value="提交">
    </form>
</body>
</html>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值