美文网首页Node.js
Node.js基础入门05

Node.js基础入门05

作者: 青昀_ | 来源:发表于2021-03-04 19:10 被阅读0次

node笔记 --祈粼

用formidable上传文件

const http = require('http');
const formidable = require('formidable');  // 处理表单数据
const fs = require('fs')
const path = require('path')
const sd = require("silly-datetime");

const server = http.createServer((req, res) => {
    if (req.url === '/api/upload' && req.method.toLowerCase() === 'post') {
        // parse a file upload
        const form = formidable({ multiples: true });
        // 设置上传文件存放的文件夹,默认为系统的临时文件夹,可以使用fs.rename()来改变上传文件的存放位置和文件名
        form.uploadDir = './images'
        // 表单全部加载完毕 执行form.parse
        form.parse(req, (err, fields, files) => {
            // fields 表单数据  fields.name fields.age fields.xxxxx
            // files 里面单个文件的时候是对象,多个文件的时候是数组,名字是input标签上name的值

            // 获取当前路径
            let oldPath = __dirname + '/' + files.multipleFiles.path
            // __dirname 是当前模块的目录名
            let now = sd.format(new Date(), 'YYYYMMDDHHmmss')
            let ran = parseInt((Math.random() * 10000).toFixed(0));
            let extname = path.extname(files.multipleFiles.name)
            let newPath = __dirname + '/images/' + now + ran + extname
            // fs.rename 异步地把 oldPath 文件重命名为 newPath 提供的路径名。 如果 newPath 已存在,则覆盖它。 除了可能的异常,完成回调没有其他参数。
            fs.rename(oldPath, newPath, err => {
                if (err) throw err
                console.log('重命名完成')
            })

            res.writeHead(200, { 'content-type': 'application/json' });
            res.end(JSON.stringify({ fields, files }, null, 2));
        });

        return;
    }

    // show a file upload form
    res.writeHead(200, { 'content-type': 'text/html' });
    res.end(`
    <h2>With Node.js <code>"http"</code> module</h2>
    <form action="/api/upload" enctype="multipart/form-data" method="post">
      <div>Text field title: <input type="text" name="title" /></div>
      <div>File: <input type="file" name="multipleFiles" multiple="multiple" /></div>
      <input type="submit" value="Upload" />
    </form>
  `);
});

server.listen(8080, () => {
    console.log('Server listening on http://localhost:8080/ ...');
});

相关文章

网友评论

    本文标题:Node.js基础入门05

    本文链接:https://www.haomeiwen.com/subject/vbgkqltx.html