Bài viết

Kho tài liệu và bài viết được chia sẻ, đánh giá bởi cộng đồng

Upload file lên server NodeJS

Vo Tan Duc đã tạo 13:01 05-02-2022 1.049 lượt xem 0 bình luận

Nội dung bài viết

- 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")
});
//multer
var multer=require("multer");
//Khai báo nơi lưu trữ file sau khi tải lên
var storage=multer.diskStorage({
    //Chỉ ra thư mục lưu file tải lên
    destination:function(req,file,cb){
        //Thư mục upload dùng để lưu trữ file
        cb(null,"./upload")
    },
    //Đặt tên file
    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

Nội dung bài viết

Bình luận

Để bình luận, bạn cần đăng nhập bằng tài khoản Howkteam.

Đăng nhập

Câu hỏi mới nhất