nodejs express+ejs+formidable实现文件上传

一人行者 万人追随

nodejs express+ejs+formidable实现文件上传

刚才做例子的时候遇到不少的问题:
1.表单提交的时候enctype=”multipart/form-data”(当有文件的时候需要加这个属性)
想问使用body-parser模块解析获取的参数是发现无法解析,prase回调中才能获取参数,去掉enctype=”multipart/form-data”
就可以了,参考 multer模块
2.Error: maxFileSize exceeded, received 2109740 bytes of file data
文件默认大小为2M 设置错误:form.maxFieldsSize = 20 * 1024 * 1024;
正确设置文件大小:form.maxFileSize = 20 * 1024 * 1024;
3.传多件的时候 只传一个文件获取的为一个对象,多个文件的时候问一个数组

express+ejs+formidable +bootstrap

ejs文件

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="/bootstrap/css/bootstrap.css">
        <script type="text/javascript" src="/bootstrap/js/jquery.min.js"></script>
        <script type="text/javascript" src="/bootstrap/js/bootstrap.js"></script>
        <script type="text/javascript" src="/bootstrap/js/index.js"></script>
    </head>
    <body>
    <nav class="navbar navbar-default">
        <!-- We use the fluid option here to avoid overriding the fixed width of a normal container within the narrow content columns. -->
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-6" aria-expanded="true">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">Brand</a>
            </div>
            <div class="navbar-collapse collapse in" id="bs-example-navbar-collapse-6" aria-expanded="true">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="http://localhost:8888/">Home</a></li>
                    <li><a href="http://localhost:8888/file">上传</a></li>
                    <li><a href="#">Link</a></li>
                </ul>
            </div><!-- /.navbar-collapse -->
        </div>
    </nav>
    <div class="row">
        <% if(value==1) {for(var i=0;i < arr.length;i++){%>
        <div class="aa col-xs-6 col-md-3">
            <a href="#" class="thumbnail">
                <img src="images/saber.jpg" alt="...">
            </a>
            <h3 style="text-align: center"><%=arr[i]%></h3>
        </div>
        <%}}%>


        <%if(value==4){%>
        <form action="http://localhost:8888/fileUpload" method="post" onsubmit="return submitFun(this)" class="form-horizontal col-xs-6 col-md-3 col-xs-offset-1 col-md-offset-1"  enctype="multipart/form-data">
            <div class="form-group">
            <select class="form-control" name="url">
                <%for(var j = 0;j <arr.length;j++){%>
                    <option value="<%=arr[j]%>"><%=arr[j]%></option>
                 <%}%>
                </select>
            </div>
            <div class="form-group">
                <label for="exampleInputFile">File input</label>
                <input type="file" id="InputFile" name="InputFile" multiple="multiple"/>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" class="btn btn-default">Sign in</button>
                </div>
            </div>
        </form>
        <%}%>
    </div>
    <script>
        //限制上传文件不能为空
        function submitFun(aaa){
            if(aaa.InputFile.value ==""){
                alert("请上传文件")
                return false
            }
            return true
        }
    </script>
    </body>
</html>

app.js启动文件

var express = require("express");
var router = require("./routes/router");
var formidable = require("node-formidable")
var ejs = require("ejs");
var fs = require("fs");
var path = require("path");

//date format工具
var dateutil = require("dateutil")
var app = express();

//设置view 默认会读(views)
app.set("view engine","ejs");

//修改默认路径为view
app.set("views","view");

//设置静态资源读取路径()
app.use(express.static("./public"))


app.get("/",router.showIndex);

app.get("/picture",router.eranPicture)

app.get("/file",router.earnFile)

app.post("/fileUpload",function (req,res) {
    if(req.url == "/favicon.ico") {
        res.end();
        return;
    }
    var form = new formidable.IncomingForm()
    //文件保留后最美
    form.keepExtensions = true;
    //多文件上传
    form.multiples=true;
    //临时文件目录
    form.uploadDir = "./public/baocun";
    //设置上传文件的大小
    form.maxFileSize = 20 * 1024 * 1024;
    //设置参数的大小
    //form.maxFieldsSize = 20 * 1024 * 1024;
    var files = [];
    form.on('file', function (filed, file) {
        files.push([filed, file]);
    })
    console.log(form.maxFieldsSize);
    form.parse(req, function(err, fields, files) {
        if(err){
            console.log(err);
        }
       console.log(fields);
        console.log(files);

        if(files.InputFile == undefined){
           res.end();
             return;
        }
        Date.prototype.format = dateutil.format;
        console.log(files.InputFile instanceof Array);
        if(files.InputFile instanceof Array) {
            for (var cc = 0; cc < files.InputFile.length; cc++) {
                var str = new Date().format('Y-m-d-h-s') + parseInt(Math.random() * 123213 + 1111) + path.extname(files.InputFile[cc].name);
                console.log(str);
                fs.rename(files.InputFile[cc].path, "./public/file/" + fields.url + "/" + str, function (err) {
                    if (err) console.log(err)

                });
            }
        }else {
            var str = new Date().format('Y-m-d-h-s') + parseInt(Math.random() * 123213 + 21111) + path.extname(files.InputFile.name);
            console.log(str);
            fs.rename(files.InputFile.path, "./public/file/" + fields.url + "/" + str, function (err) {
                if (err) console.log(err)
            });
        }
        router.showIndex(req,res);
    });
})

app.listen(8888)

router.js model(处理业务)

var fs = require("fs");
var formidable = require("node-formidable")
exports.showIndex = function (req,res) {
    if(req.url&&req.url == "/favicon.ico") {
        res.end();
        return;
    }
    var url = "./public/file/"
    var arr = fs.readdirSync(url)
    var data = {};
    data.arr = arr;
    data.value = 1
    res.render("index",data);
    res.end();
}

exports.eranPicture = function (req,res) {
    if(req.url == "/favicon.ico") {
        res.end();
        return;
    }
    var url = "./public/file/" + req.query.url;
    var arr = fs.readdirSync(url);
    var data = {};
    data.url = req.query.url
    data.arr = arr;
    data.value = 2;
    res.send(data)
    res.end();
}

exports.earnFile = function (req,res) {
    if(req.url == "/favicon.ico") {
        res.end();
        return;
    }
    var url = "./public/file/"
    var arr = fs.readdirSync(url)
    var data = {};
    data.url = req.query.url
    data.arr = arr;
    data.value = 4;
    res.render("index",data);
    res.end();
}


//代码gitHub地址:https://github.com/daiyoucheng/photo
以下是一个基于 NodejsExpressEJS 的分页查询实现示例: 首先,安装必要的依赖: ``` npm install express ejs mongoose express-flash express-session ``` 然后,创建一个名为 `app.js` 的文件,引入所需模块: ```javascript const express = require('express'); const mongoose = require('mongoose'); const session = require('express-session'); const flash = require('express-flash'); const bodyParser = require('body-parser'); const app = express(); const port = process.env.PORT || 3000; // 连接 MongoDB 数据库 mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true}); // 定义数据库模型 const Article = mongoose.model('Article', { title: String, content: String, created_at: Date }); // 设置模板引擎和静态文件目录 app.set('view engine', 'ejs'); app.use(express.static(__dirname + '/public')); // 设置 session 和 flash app.use(session({ secret: 'mysecretkey', resave: true, saveUninitialized: true })); app.use(flash()); // 设置 bodyParser app.use(bodyParser.urlencoded({ extended: true })); // 定义路由 app.get('/', async function(req, res) { const perPage = 5; const page = req.query.page || 1; const articles = await Article.find() .skip((perPage * page) - perPage) .limit(perPage); const count = await Article.countDocuments(); const totalPages = Math.ceil(count / perPage); res.render('index', { articles: articles, current: page, pages: totalPages }); }); app.listen(port, function() { console.log('Server listening on port ' + port); }); ``` 在 `views` 文件夹中创建一个名为 `index.ejs` 的文件,用于显示分页数据: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>分页查询</title> </head> <body> <h1>文章列表</h1> <% if (articles.length > 0) { %> <ul> <% articles.forEach(function(article) { %> <li><%= article.title %></li> <% }); %> </ul> <% } else { %> <p>没有文章。</p> <% } %> <% if (pages > 1) { %> <div class="pagination"> <ul> <% if (current == 1) { %> <li class="disabled"><span>«</span></li> <% } else { %> <li><a href="?page=<%= current - 1 %>">«</a></li> <% } %> <% for (var i = 1; i <= pages; i++) { %> <% if (i == current) { %> <li class="active"><span><%= i %></span></li> <% } else { %> <li><a href="?page=<%= i %>"><%= i %></a></li> <% } %> <% } %> <% if (current == pages) { %> <li class="disabled"><span>»</span></li> <% } else { %> <li><a href="?page=<%= current + 1 %>">»</a></li> <% } %> </ul> </div> <% } %> </body> </html> ``` 在上面的示例中,我们使用了 `mongoose` 连接 MongoDB 数据库,并定义了一个名为 `Article` 的数据库模型。在路由中,我们使用 `await` 关键字来等待查询结果,并通过 `skip()` 和 `limit()` 方法来实现分页查询。在视图中,我们使用 EJS 模板引擎来生成分页链接。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值