node.js 实现简单的文件上传功能

本文主要采用node express框架实现,模板引擎用的是EJS
这是app.js文件

const express = require('express');
const cookieParser = require('cookie-parser');
const sessionParser = require('cookie-session');
const consolidate = require('consolidate');
const path = require('path');
const bodyParser = require('body-parser');
const multer = require('multer');
const fs = require('fs');

var app = express();
//配置模板引擎
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', consolidate.ejs);


//解析cookie
app.use(cookieParser('sdadadasdasdasdas21312'));

//解析session
var keyArr = [];
for(var i = 0;i<100000;i++){
    keyArr.push('keys_'+ Math.random());
}
app.use(sessionParser({name:'index_id', keys:keyArr, maxAge:3600*60*20}))

//解析post数据
app.use(bodyParser.urlencoded({extended:false}));

//解析post文件
var objMulter = multer({dest:'./public/upload'})
app.use(objMulter.any());
//转发静态资源
app.use('/satic', express.static(path.join('public')));

//返回主页
app.get('/', (req, res) => {
    console.log(req.query, req.body, req.cookies, req.session)
    res.render('index',{name:'index'});
})


 /*   [ { fieldname: 'file',
    originalname: 'back.jpg',
    encoding: '7bit',
    mimetype: 'image/jpeg',
    destination: './public/upload',
    filename: '6c863b25d379a6f9d61e2495c2e03206',
    path: 'public\\upload\\6c863b25d379a6f9d61e2495c2e03206',
    size: 43300 } ] */

//上传文件
app.use('/file', (req, res) => {
    var oldName = req.files[0].path;
    var newName = oldName + path.parse(req.files[0].originalname).ext;
    //console.log("ext",path.parse(req.files[0].origial).ext)
    fs.rename(oldName, newName, (err) => {
        if(err){
            res.send('err');
        }else{
            res.send('success');
        }
    })
})
//监听端口
var server = app.listen('8000', function (req, res) { 
    var port = server.address().port;
    console.log('success in port:' + port);
 })

这是form.html文件


<html lang="zh-cn">

<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>首页title>
    <style>
        .container{
         height: 400px;
         width: 400px;
         background-color: gainsboro;
     }
    style>
head>

<body>
    <span>这是<%=name%>页面span>
    <form action="/file" method="POST" enctype="multipart/form-data">
        <div class="container">
            <input type="file" name="file">
            <button type="submit" id="upload">上传button>
        div>
    form>

body>

html>

你可能感兴趣的:(node.js,express)