- B1: Ngoài desktop, tạo 1 thư mục
- B2: Mở cmd, cd vào thư mục đó
- B3:Trong cmd, gõ: npm init để tạo project
- B4: Cài đặt gói express, ejs và multer: npm install express ejs multer
- B5: Tạo file index.js (dùng để làm server) trong thư mục đã tạo ở B1
- B6: Trong folder đã tạo ở B1, tạo folder views
- B7: Trong folder views, tạo 1 file trangchu.ejs để code html và javascript
Code index.js:
var express=require("express");
var app=express();
app.use(express.static("pubic"));
app.set("view engine","ejs");
app.set("views","./views");
var server=require("http").Server(app);
server.listen(3000);
app.get("/",function(req,res){
res.render("trangchu")
});
var multer=require("multer");
var storage=multer.diskStorage({
destination:function(req,file,cb){
cb(null,"./upload")
},
filename:function(req,file,cb){
cb(null,file.originalname)
}
})
var upload=multer({storage:storage});
app.post("/upload",upload.single("file"),function(req,res){
console.log(req.file)
res.send("Upload File Succefully")
})
Code trangchu.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload File</title>
</head>
<body>
<form action="http://localhost:3000/upload" method="Post" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="upload">
</form>
</body>
</html>
Chạy project:
- B1: Mở cmd, gõ: node index.js
- B2: Trên thanh url của trình duyệt web, gõ: http://localhost:3000