บทความนี้จะแนะนำการเขียนสคริปต์เพื่อ Upload ไฟล์เข้าสู่ Server ด้วยมอดูล multer ซึ่งจะเป็นมอดูลหลักในการช่วยให้เรา Upload ไฟล์ต่างๆ ได้สะดวกมากขึ้น โดยขอเริ่มจากติดตั้งมอดูลที่จำเป็นต้องใช้งาน express, ejs, multer
npm i express
npm i ejs
npm i multer
สร้างโฟลเดอร์ public แล้วใส่ข้อมูลเกี่ยวกับ bootstrap ทั้งหมด และสร้างโฟลเดอร์ uploads เพื่อเก็บข้อมูลไฟล์หรือรูปภาพที่ได้ทำการอัปโหลดจากเครื่องผู้ใช้ จากนั้นสร้างฟอร์มสำหรับ Upload ไฟล์
สคริปต์ views/upload.ejs สร้างฟอร์มสำหรับ Upload ไฟล์ โดยกำหนดชื่อตัวแปร fileupload เพื่อนำไปใช้ในส่วนการ upload ไฟล์
<!DOCTYPE html> <html> <head> <title>Upload File </title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="./bootstrap/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="page-header"> <h1>Upload File</h1> <hr> </div> <div class="row"> <div class="col"> <form method="post" action="/upload" enctype="multipart/form-data"> <div class="form-group"> <label for="firstname">Upload</label> <input type="file" class="form-control" name="fileupload" required> </div> <button type="submit" class="btn btn-primary">Submit</button> <button type="reset" class="btn btn-primary">Reset</button> </form> </div> </div> </div> <script src="./jquery-3.2.1.slim.min.js" ></script> <script src="./popper.min.js" ></script> <script src="./bootstrap/dist/js/bootstrap.min.js"></script> </body> </html>
จากนั้นสร้างสคริปต์ index.js ซึ่งจะเป็นสคริปต์ในการ Upload ไฟล์
สคริปต์ index.js
const express = require('express') const app = express() app.use(express.static(__dirname + '/public')) app.set('view engine', 'ejs') const bodyParser = require('body-parser') app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) const multer = require('multer') const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, './public/uploads') }, filename: (req, file, cb) => { cb(null, 'file-' + Date.now() + '.' + file.originalname.split('.')[file.originalname.split('.').length-1])} }) const upload = multer({ storage: storage }) app.get('/', (req, res) => { res.render('upload') }) app.post('/upload',upload.single('fileupload'),(req,res) => { res.render('show',req.file) }) app.listen(3000, () => { console.log('Server Started on localhost:3000...') })
จากสคริปต์ index.js เราจะต้องเรียกใช้มอดูล multer เก็บไว้ในตัวแปร multer
จากนั้นต้องกำหนดข้อมูลที่เกี่ยวของ destination เป็นการกำหนดโฟลเดอร์สำหรับเก็บไฟล์ที่ผู้ใช้ Upload เข้ามาซึ่งในตัวอย่างนี้จะเก็บไว้ที่ /public/uploads
filename เป็นการกำหนดชื่อไฟล์หลังจาก uploads ในตัวอย่างนี้จะกำหนดชื่อไฟล์เริ่มต้นด้วยข้อความ "file-" ต่อด้วยวันเดือนปีที่ upload และหานามสกุลไฟล์ต้นฉบับ
'file-' + Date.now() + '.' + file.originalname.split('.')[file.originalname.split('.').length-1])
โดยการกำหนดค่าทั้งหมดที่กล่าวมาจะเก็บไว้ในตัวแปร storage แล้วไปใช้กับมอดูล multer เก็บไว้ในตัวแปร upload
const upload = multer({ storage: storage })
จากนั้นเมื่อรันสคริปต์ก็จะแสดงหน้าฟอร์ม โดยสคริปต์จะไปเรียกใช้ไฟล์ upload.ejs ออกมา ดังภาพ
app.get('/', (req, res) => { res.render('upload') })
จากนั้นหากผู้ใช้ upload ไฟล์แล้วกดปุ่ม submit ก็จะส่งมายังหน้า upload method post
app.post('/upload',upload.single('fileupload'),(req,res) => { res.render('show',req.file) })
โดยเราสามารถนำตัวแปรไปใช้งานได้ เช่น filename ชื่อไฟล์ที่เรา Upload เสร็จแล้ว size ขนาดของไฟล์ originalname ชื่อไฟล์ต้นฉบับ ฯลฯ
Key | Description | Note |
---|---|---|
fieldname | Field name specified in the form | |
originalname | Name of the file on the user's computer | |
encoding | Encoding type of the file | |
mimetype | Mime type of the file | |
size | Size of the file in bytes | |
destination | The folder to which the file has been saved | DiskStorage |
filename | The name of the file within the destination | DiskStorage |
path | The full path to the uploaded file | DiskStorage |
buffer | A Buffer of the entire file | MemoryStorage |
สคริปต์ views/show.ejs แสดงภาพที่ upload มา
<!DOCTYPE html> <html> <head> <title> Upload File </title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="./bootstrap/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="page-header"> <h1>Upload File</h1> <hr> </div> <div class="row"> <div class="col"> <img src="uploads/<%=filename%>" width="250"> </div> </div> </div> <script src="./jquery.min.js"></script> <script src="./bootstrap/js/bootstrap.min.js"></script> </body> </html>
สรุป
การ upload ไฟล์ด้วยใช้มอดูล multer ในตัวอย่างนี้จะ upload ไฟล์ได้ครั้งละ 1 ไฟล์เท่านั้น ซึ่งมอดูล multer สามารถ upload ไฟล์ครั้งละหลายๆ ไฟล์ โดยสามารถเข้าไปดูรายละเอียดเพิ่มเติมได้ที่ https://www.npmjs.com/package/multer
Top comments (0)