02.node上传文件 文件处理 服务器渲染

上传文件 文件处理 服务器渲染

插件:formidable
安装指令:

cnpm i formidable -S

用法:
app.js

const express = require('express');
const fs = require('fs');
const formidable = require('formidable');
const path = require('path');

let app = express();
let router = express.Router();

app.use(router)
// 暴露public下的文件( 访问直接服务器地址加文件地址就可以 如:http://localhost:8888/index.js 就行)
app.use(express.static('./public'))
app.use(express.static('./images'))
app.listen(8888)

app.engine('.html', require('express-art-template'))
app.set('view engine', '.html')

app.set('view options', {
    debug: process.env.NODE_ENV !== 'production'
})

let dataList = [
    { name: '赵云', img: '1.jpg' },
    { name: '吕布', img: '2.jpg' },
    { name: '大桥', img: '3.jpg' },
    { name: '曹操', img: '4.jpg' },
    { name: '关羽', img: '5.jpg' }
];

router
    .get("/", (req, res) => {
        // index.html 是当前文件夹 views 下的 index.html
        res.render('index.html', { list: dataList });
    })
    .post('/add', (req, res, next) => {
        // 解析文件用 formidable
        let form = new formidable.IncomingForm();
        //  配置 指定上传路径
        form.uploadDir = path.join(__dirname, '/images');
        //  配置 保持原有后缀名
        form.keepExtensions = true;
        
        form.parse(req, (err, fields, files) => {
            console.log(files);
            // console.log(fields);
            let name = fields.name;
            let fileName = path.parse(files.headImg.path).base;
            dataList.push({name, img: fileName});
            res.redirect('/');
        });
    })

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .img{
            width: 40px;
        }
    </style>
</head>
<body>
    <ul>
        {{ each list }}
        <li>
            <img src="{{ $value.img }}" class="img">
            {{ $value.name }}
        </li>
        {{ /each }}
    </ul>

    // 上传文件必须加 enctype="multipart/form-data" 属性
    <form action="/add" method="post" enctype="multipart/form-data">
        名字:<input type="text" name="name" id="">
        头像:<input type="file" name="headImg" id="">
        <button>提交</button>
    </form>


    <script src="index.js"></script>
</body>
</html>

第7集 0分钟

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值