22 October 2019

NodeJS ExpressJS: Upload Files [EX-20]

Upload Files

/views/users/create.pug
create.pug
extends ../layouts/common.pug 

block content
    if errors
        each error in errors
             .m-auto.col-6.alert.alert-danger=  error

    h1(class="text-center") Create User
    form(action="/users/create" method="POST" enctype="multipart/form-data")
        div(class="col-6 m-auto")
            div(class="form-group")
                label Name
                input(name="name", type="text", autocomplete="off" class="form-control" placeholder="Enter name")
            div(class="form-group")
                label Address
                input(type="text" name="address" autocomplete="off" class="form-control" placeholder="Enter email")
            div(class="form-group")
                label Phone
                input(type="text" name="phone" autocomplete="off" class="form-control" placeholder="Enter phone")
            div(class="form-group")
                label Email
                input(type="email" name="email" autocomplete="off" class="form-control" placeholder="Enter email")
            div(class="form-group")
                label Password
                input(type="password" name="password" autocomplete="off" class="form-control" placeholder="Enter password")
            div(class="form-group")
                label Avatar
                input(type="file" name="avatar" class="form-control")
            a(href="/users") 
                button(type="button" class="btn btn-info") << back
            button(type="submit" class="btn btn-success float-right") Create User
/controller/user.controller.js
user.controller.js
const db = require('../db/index').lowDB;
const ids = require('short-id');
const md5 = require('md5');

module.exports.index = function (req, res) {
    res.render('users/index', {
        users: db.get('users').value()
    })
}

module.exports.create = function (req, res) {
    res.render('users/create')
}

module.exports.postCreate = function (req, res) {
    // Add a post
    req.body.id = ids.generate();
    req.body.avatar = req.file.path.split('\\').slice(1).join('/');  // path file
    req.body.password = md5(req.body.password);
    db.get('users').push(req.body).write()
    res.redirect('/users');
}

module.exports.get = function (req, res) {
    var id = req.params.id;
    res.render('users/view', {
        user: db.get('users').find({
            id: id
        }).value()
    })
}

module.exports.search = function (req, res) {
    var q = req.query.name;
    var matchUsers = db.get('users').value().filter(f => f.name.toLocaleLowerCase().indexOf(q.toLocaleLowerCase()) !== -1);
    res.render('users/index', {
        users: matchUsers
    })
}

npm install --save multer

Sử dụng multer module xử lý vấn đề gửi form data dạng post enctype="multipart/form-data"
upload.single('avatar') có nghĩa là chỉ có name="avatar" là gửi dạng file
Lưu file dạng binary

/routes/user.route.js
user.route.js
const express = require('express')
const router = express()
var multer  = require('multer')

var upload = multer({ dest: './public/uploads/' })

var controller = require('../controller/user.controller');

var validate = require('../validate/user.validate');

// GET method route
router.get('/', controller.index);

// GET method route
router.get('/create', controller.create);

// GET by id
router.get('/:id', controller.get);

// POST create user
router.post('/create', upload.single('avatar'), validate.postCreate, controller.postCreate);

// GET method route
router.get('/search/name', controller.search);

module.exports = router;
Layout
/views/users/index.pug
index.pug
extends ../layouts/common.pug 

block content
    h1(class="text-center") User Managerment
    a(href='/users/create') 
        Button(class="btn btn-info") Create User

    form(action = "/users/search/name", method="GET")
        div(class="input-group mb-3 col-4 float-right")
            input(name="name", type="text", autocomplete="off" class="form-control" placeholder="Enter search")
            div(class="input-group-append")
                button(class="btn btn-success") Search

    table(class="table table-hover")
        thead
            tr
                th(scope="col") Name
                th(scope="col") Address
                th(scope="col") Phone
                th(scope="col") Email
                th(scope="col") 
        tbody
            each user in users
                tr
                    th(scope="row")= user.name
                    td= user.address 
                    td= user.phone
                    td= user.email
                    td 
                        img(src=user.avatar width="40")
                    td
                        a(class="float-right" href='users/'+ user.id) View
/views/users/view.pug
view.pug
extends ../layouts/common.pug 

block content
    div(class="col-6 m-auto")
        h1(class="text-center") View User Info
        div(class="text-center")
            img(src=`../`+user.avatar width="140")
        div(class="form-group")
            label Name
            input(type="text", value= user.name, autocomplete="off" class="form-control" disabled)
        div(class="form-group")
            label Addres
            input(type="text" value= user.address, autocomplete="off" class="form-control" disabled)
        div(class="form-group")
            label Email
            input(type="text" value= user.email,  autocomplete="off" class="form-control" disabled)
        div(class="form-group")
            label Phone
            input(type="text" value= user.phone, autocomplete="off" class="form-control" disabled)
        a(href="/users") 
            button(type="button" class="btn btn-info") << back
<< back | next >> 

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang