Tôi đang sử dụng Multer để tải lên tệp và XLSX để xử lý nó và MongoDB làm cơ sở dữ liệu [Mongoose cho mô hình]:
"Content-disposition" : "attachment; filename=[yourFileName]"
"Content-Type" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
3 là mô hình dữ liệu, bạn phải thêm tên cột Excel. Xem tài liệu Mongoose để biết thêm thông tinconst express = require["express"];
const multer = require["multer"];
const connectDB = require["./config/db"];
const Lead = require["./models/Lead"];
connectDB[];
const uploadXLSX = async [req, res, next] => {
try {
let path = req.file.path;
var workbook = XLSX.readFile[path];
var sheet_name_list = workbook.SheetNames;
let jsonData = XLSX.utils.sheet_to_json[
workbook.Sheets[sheet_name_list[0]]
];
if [jsonData.length === 0] {
return res.status[400].json[{
success: false,
message: "xml sheet has no data",
}];
}
let savedData = await Lead.create[jsonData];
return res.status[201].json[{
success: true,
message: savedData.length + " rows added to the database",
}];
} catch [err] {
return res.status[500].json[{ success: false, message: err.message }];
}
};
var storage = multer.diskStorage[{
destination: function [req, file, cb] {
cb[null, "uploads"];
},
filename: function [req, file, cb] {
cb[null, Date.now[] + "-" + file.originalname];
},
}];
const upload = multer[{ storage: storage }];
app.post["/upload", upload.single["xlsx"], uploadXLSX];
const port = process.env.PORT || 5000;
const server = app.listen[port, [] => {
console.log["app running on port", port];
}];
Vì vậy, từ đây khi bạn thực hiện cuộc gọi đến
"Content-disposition" : "attachment; filename=[yourFileName]"
"Content-Type" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
4 với người đưa thư xem hình bên dướiTệp Excel là định dạng tệp bảng tính do Microsoft tạo để sử dụng với Microsoft Excel. Bạn có thể sử dụng tệp để tạo, xem, chỉnh sửa, phân tích dữ liệu, biểu đồ, ngân sách và nhiều hơn nữa. Trong hướng dẫn này, tôi sẽ chỉ cho bạn cách tải lên/nhập dữ liệu tệp Excel vào cơ sở dữ liệu MySQL bằng Node.js & Read-Excel-File.
Các bài viết liên quan: - Tải lên/lưu trữ hình ảnh trong MySQL bằng Node.js, Express & Multer - Cách tải lên/lưu trữ hình ảnh trong MongoDB bằng Node.js, Express & Multer - Nhập dữ liệu CSV vào MySQL bằng Node.js - Nhập dữ liệu CSV vào PostgreSQL Sử dụng Node.js - Nhập tệp CSV vào Bộ sưu tập MongoDB bằng Node.js
–
Upload/store images in MySQL using Node.js, Express & Multer
– How to upload/store images in MongoDB using Node.js, Express & Multer
– Import CSV data into MySQL using Node.js
–
Import CSV data into PostgreSQL using Node.js
– Import CSV file into MongoDB collection using Node.js
Thay vào đó, tệp CSV: Node.js: Tải dữ liệu tệp CSV vào cơ sở dữ liệu với Express
Node.js: Upload CSV file data into Database with Express
Nội dung
- Node.js REST API để tải lên các tệp excel
- API Node.js REST trả về tệp Excel
- Công nghệ
- Cấu trúc dự án
- Thiết lập dự án tải lên tệp excel excel.js
- Định cấu hình cơ sở dữ liệu MySQL & phần tiếp theo
- Khởi tạo phần tiếp theo
- Xác định mô hình phần tiếp theo
- Tạo phần mềm trung gian để tải lên và lưu trữ tệp Excel
- Tạo bộ điều khiển để tải lên/nhập tệp Excel
- Xác định các tuyến đường để tải lên tệp excel
- Tạo máy chủ ứng dụng Express
- Chạy & Kiểm tra
- Sự kết luận
- Đọc thêm
- Mã nguồn
Node.js REST API để tải lên các tệp excel
API Node.js REST trả về tệp Excel.xlsx file that contains Tutorial data in Tutorials sheet as following:
Công nghệ
- Cấu trúc dự án
- Thiết lập dự án tải lên tệp excel excel.js
- Định cấu hình cơ sở dữ liệu MySQL & phần tiếp theo
Khởi tạo phần tiếp theo
Xác định mô hình phần tiếp theo
API Node.js REST trả về tệp Excel
Công nghệtutorials.xlsx that contains data in MySQL table:
Cấu trúc dự án
You need to set the HTTP header:
"Content-disposition" : "attachment; filename=[yourFileName]"
"Content-Type" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Thiết lập dự án tải lên tệp excel excel.js
Node.js Download Excel file example with exceljs
Định cấu hình cơ sở dữ liệu MySQL & phần tiếp theo
Tạo bộ điều khiển để tải lên/nhập tệp Excel | Xác định các tuyến đường để tải lên tệp excel | Tạo máy chủ ứng dụng Express |
Chạy & Kiểm tra | Sự kết luận | Đọc thêm |
Chạy & Kiểm tra | Sự kết luận | Đọc thêm |
Công nghệ
- Cấu trúc dự án
- Thiết lập dự án tải lên tệp excel excel.js
- Định cấu hình cơ sở dữ liệu MySQL & phần tiếp theo
- Khởi tạo phần tiếp theo
- Xác định mô hình phần tiếp theo
Cấu trúc dự án
Thiết lập dự án tải lên tệp excel excel.js
Định cấu hình cơ sở dữ liệu MySQL & phần tiếp theo
–
"Content-disposition" : "attachment; filename=[yourFileName]"
"Content-Type" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
7: uses configuration above to initialize Sequelize, "Content-disposition" : "attachment; filename=[yourFileName]"
"Content-Type" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
8 for Sequelize Tutorial data model.–
"Content-disposition" : "attachment; filename=[yourFileName]"
"Content-Type" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
9: initializes Multer Storage engine and defines middleware function to save Excel file in npm install express multer sequelize mysql2 read-excel-file
0 folder.–
npm install express multer sequelize mysql2 read-excel-file
1:- Sử dụng
2 để đọc tệp Excel trong thư mụcnpm install express multer sequelize mysql2 read-excel-file
0, sau đó lưu dữ liệu vào cơ sở dữ liệu MySQL với mô hình tiếp theo.npm install express multer sequelize mysql2 read-excel-file
- Chức năng xuất để truy xuất tất cả các hướng dẫn trong bảng cơ sở dữ liệu
-
npm install express multer sequelize mysql2 read-excel-file
4: Xác định các tuyến đường cho các điểm cuối được gọi từ máy khách HTTP, các bộ điều khiển sử dụng [cùng với phần mềm trung gian] để xử lý các yêu cầu. - npm install express multer sequelize mysql2 read-excel-file
5: Khởi tạo các tuyến đường, chạy ứng dụng Express.–
npm install express multer sequelize mysql2 read-excel-file
5: initializes routes, runs Express app.Thiết lập dự án tải lên tệp excel excel.js
Mở dấu nhắc lệnh, thay đổi thư mục hiện tại thành thư mục gốc của dự án của chúng tôi. Cài đặt Express, Multer, Sequelize, MySQL2 với lệnh sau:
Install Express, Multer, Sequelize, Mysql2 with the following command:
npm install express multer sequelize mysql2 read-excel-file
Tệp gói.json sẽ trông như thế này:package.json file will look like this:
{
"name": "node-js-upload-download-excel-files",
"version": "1.0.0",
"description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File",
"main": "src/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node js",
"upload",
"import",
"download",
"excel",
"files",
"mysql",
"database"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"multer": "^1.4.2",
"mysql2": "^2.1.0",
"read-excel-file": "^4.0.6",
"sequelize": "^5.21.13"
}
}
Định cấu hình cơ sở dữ liệu MySQL & phần tiếp theo
Trong thư mục SRC, chúng tôi tạo một thư mục cấu hình riêng cho cấu hình với tệp db.config.js như thế này:src folder, we create a separate config folder for configuration with db.config.js file like this:
module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
Năm tham số đầu tiên là cho kết nối MySQL.
npm install express multer sequelize mysql2 read-excel-file
6 là tùy chọn, nó sẽ được sử dụng cho cấu hình nhóm kết nối tiếp theo:npm install express multer sequelize mysql2 read-excel-file
6 is optional, it will be used for Sequelize connection pool configuration:
7: Số lượng kết nối tối đa trong nhómnpm install express multer sequelize mysql2 read-excel-file
8: Số lượng kết nối tối thiểu trong nhómnpm install express multer sequelize mysql2 read-excel-file
9: Thời gian tối đa, tính bằng mili giây, rằng một kết nối có thể nhàn rỗi trước khi được phát hànhnpm install express multer sequelize mysql2 read-excel-file
0: Thời gian tối đa, tính bằng mili giây, nhóm đó sẽ cố gắng kết nối trước khi ném lỗi{ "name": "node-js-upload-download-excel-files", "version": "1.0.0", "description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File", "main": "src/server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "node js", "upload", "import", "download", "excel", "files", "mysql", "database" ], "author": "bezkoder", "license": "ISC", "dependencies": { "express": "^4.17.1", "multer": "^1.4.2", "mysql2": "^2.1.0", "read-excel-file": "^4.0.6", "sequelize": "^5.21.13" } }
Để biết thêm chi tiết, vui lòng truy cập tham chiếu API cho hàm tạo phần tiếp theo.
Khởi tạo phần tiếp theo
Bây giờ chúng tôi khởi tạo phần tiếp theo trong thư mục SRC/Model.src/models folder.
Tạo src/model/index.js với mã sau:src/models/index.js with the following code:
const dbConfig = require["../config/db.config.js"];
const Sequelize = require["sequelize"];
const sequelize = new Sequelize[dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
}];
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.tutorials = require["./tutorial.model.js"][sequelize, Sequelize];
module.exports = db;
Chúng tôi sẽ xác định mô hình
{
"name": "node-js-upload-download-excel-files",
"version": "1.0.0",
"description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File",
"main": "src/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node js",
"upload",
"import",
"download",
"excel",
"files",
"mysql",
"database"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"multer": "^1.4.2",
"mysql2": "^2.1.0",
"read-excel-file": "^4.0.6",
"sequelize": "^5.21.13"
}
}
1 trong bước tiếp theo.Xác định mô hình phần tiếp theo
Trong thư mục mô hình, hãy tạo tệp hướng dẫn.model.js như thế này:
module.exports = [sequelize, Sequelize] => {
const Tutorial = sequelize.define["tutorial", {
title: {
type: Sequelize.STRING
},
description: {
type: Sequelize.STRING
},
published: {
type: Sequelize.BOOLEAN
}
}];
return Tutorial;
};
Mô hình phần tiếp theo này đại diện cho bảng hướng dẫn trong cơ sở dữ liệu MySQL. Các cột này sẽ được tạo tự động: id, tiêu đề, mô tả, xuất bản, createdat, cập nhật.tutorials table in MySQL database. These columns will be generated automatically: id, title, description, published, createdAt, updatedAt.
Sau khi khởi tạo phần tiếp theo, chúng tôi không cần phải viết các chức năng CRUD, phần tiếp theo hỗ trợ tất cả chúng:
- Tạo một hướng dẫn mới:
2{ "name": "node-js-upload-download-excel-files", "version": "1.0.0", "description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File", "main": "src/server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "node js", "upload", "import", "download", "excel", "files", "mysql", "database" ], "author": "bezkoder", "license": "ISC", "dependencies": { "express": "^4.17.1", "multer": "^1.4.2", "mysql2": "^2.1.0", "read-excel-file": "^4.0.6", "sequelize": "^5.21.13" } }
- Tạo nhiều hướng dẫn:
3{ "name": "node-js-upload-download-excel-files", "version": "1.0.0", "description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File", "main": "src/server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "node js", "upload", "import", "download", "excel", "files", "mysql", "database" ], "author": "bezkoder", "license": "ISC", "dependencies": { "express": "^4.17.1", "multer": "^1.4.2", "mysql2": "^2.1.0", "read-excel-file": "^4.0.6", "sequelize": "^5.21.13" } }
- Tìm hướng dẫn bằng ID:
4{ "name": "node-js-upload-download-excel-files", "version": "1.0.0", "description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File", "main": "src/server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "node js", "upload", "import", "download", "excel", "files", "mysql", "database" ], "author": "bezkoder", "license": "ISC", "dependencies": { "express": "^4.17.1", "multer": "^1.4.2", "mysql2": "^2.1.0", "read-excel-file": "^4.0.6", "sequelize": "^5.21.13" } }
- Nhận tất cả các hướng dẫn:
5{ "name": "node-js-upload-download-excel-files", "version": "1.0.0", "description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File", "main": "src/server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "node js", "upload", "import", "download", "excel", "files", "mysql", "database" ], "author": "bezkoder", "license": "ISC", "dependencies": { "express": "^4.17.1", "multer": "^1.4.2", "mysql2": "^2.1.0", "read-excel-file": "^4.0.6", "sequelize": "^5.21.13" } }
- Cập nhật, xóa các hướng dẫn
Chúng tôi sẽ sử dụng
{
"name": "node-js-upload-download-excel-files",
"version": "1.0.0",
"description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File",
"main": "src/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node js",
"upload",
"import",
"download",
"excel",
"files",
"mysql",
"database"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"multer": "^1.4.2",
"mysql2": "^2.1.0",
"read-excel-file": "^4.0.6",
"sequelize": "^5.21.13"
}
}
6 và {
"name": "node-js-upload-download-excel-files",
"version": "1.0.0",
"description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File",
"main": "src/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node js",
"upload",
"import",
"download",
"excel",
"files",
"mysql",
"database"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"multer": "^1.4.2",
"mysql2": "^2.1.0",
"read-excel-file": "^4.0.6",
"sequelize": "^5.21.13"
}
}
5 trong bộ điều khiển của chúng tôi.Tạo phần mềm trung gian để tải lên và lưu trữ tệp Excel
Bên trong thư mục phần mềm trung gian, hãy tạo tệp upload.js với mã sau:middleware folder, create upload.js file with the following code:
const multer = require["multer"];
const excelFilter = [req, file, cb] => {
if [
file.mimetype.includes["excel"] ||
file.mimetype.includes["spreadsheetml"]
] {
cb[null, true];
} else {
cb["Please upload only excel file.", false];
}
};
var storage = multer.diskStorage[{
destination: [req, file, cb] => {
cb[null, __basedir + "/resources/static/assets/uploads/"];
},
filename: [req, file, cb] => {
console.log[file.originalname];
cb[null, `${Date.now[]}-bezkoder-${file.originalname}`];
},
}];
var uploadFile = multer[{ storage: storage, fileFilter: excelFilter }];
module.exports = uploadFile;
Trong mã trên, chúng tôi đã thực hiện các bước sau: - Đầu tiên, chúng tôi nhập mô -đun
{
"name": "node-js-upload-download-excel-files",
"version": "1.0.0",
"description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File",
"main": "src/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node js",
"upload",
"import",
"download",
"excel",
"files",
"mysql",
"database"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"multer": "^1.4.2",
"mysql2": "^2.1.0",
"read-excel-file": "^4.0.6",
"sequelize": "^5.21.13"
}
}
8. - Tiếp theo, chúng tôi định cấu hình {
"name": "node-js-upload-download-excel-files",
"version": "1.0.0",
"description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File",
"main": "src/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node js",
"upload",
"import",
"download",
"excel",
"files",
"mysql",
"database"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"multer": "^1.4.2",
"mysql2": "^2.1.0",
"read-excel-file": "^4.0.6",
"sequelize": "^5.21.13"
}
}
8 để sử dụng công cụ lưu trữ đĩa. - Chúng tôi cũng xác định một bộ lọc chỉ cho phép tệp có định dạng Excel.– First, we import
{
"name": "node-js-upload-download-excel-files",
"version": "1.0.0",
"description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File",
"main": "src/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node js",
"upload",
"import",
"download",
"excel",
"files",
"mysql",
"database"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"multer": "^1.4.2",
"mysql2": "^2.1.0",
"read-excel-file": "^4.0.6",
"sequelize": "^5.21.13"
}
}
8 module.– Next, we configure
{
"name": "node-js-upload-download-excel-files",
"version": "1.0.0",
"description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File",
"main": "src/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node js",
"upload",
"import",
"download",
"excel",
"files",
"mysql",
"database"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"multer": "^1.4.2",
"mysql2": "^2.1.0",
"read-excel-file": "^4.0.6",
"sequelize": "^5.21.13"
}
}
8 to use Disk Storage engine.– We also define a filter to only allow file with excel format.
Bạn có thể thấy rằng chúng tôi có hai tùy chọn ở đây: -
module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
0 xác định thư mục để lưu trữ các tệp đã tải lên. - module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
1 Xác định tên của tệp bên trong thư mục đích. - Chúng tôi thêm tiền tố module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
2 vào tệp gốc của tệp để đảm bảo rằng các bản sao không bao giờ xảy ra.–
module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
0 determines folder to store the uploaded files.–
module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
1 determines the name of the file inside the destination
folder.– We add the
module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
2 prefix to the file’s original name to make sure that the duplicates never occur.Tạo bộ điều khiển để tải lên/nhập tệp Excel
controllers/tutorial/excel.controller.js/excel.controller.js
const db = require["../../models"];
const Tutorial = db.tutorials;
const readXlsxFile = require["read-excel-file/node"];
const upload = async [req, res] => {
try {
if [req.file == undefined] {
return res.status[400].send["Please upload an excel file!"];
}
let path =
__basedir + "/resources/static/assets/uploads/" + req.file.filename;
readXlsxFile[path].then[[rows] => {
// skip header
rows.shift[];
let tutorials = [];
rows.forEach[[row] => {
let tutorial = {
id: row[0],
title: row[1],
description: row[2],
published: row[3],
};
tutorials.push[tutorial];
}];
Tutorial.bulkCreate[tutorials]
.then[[] => {
res.status[200].send[{
message: "Uploaded the file successfully: " + req.file.originalname,
}];
}]
.catch[[error] => {
res.status[500].send[{
message: "Fail to import data into database!",
error: error.message,
}];
}];
}];
} catch [error] {
console.log[error];
res.status[500].send[{
message: "Could not upload the file: " + req.file.originalname,
}];
}
};
const getTutorials = [req, res] => {
Tutorial.findAll[]
.then[[data] => {
res.send[data];
}]
.catch[[err] => {
res.status[500].send[{
message:
err.message || "Some error occurred while retrieving tutorials.",
}];
}];
};
module.exports = {
upload,
getTutorials,
};
Bây giờ hãy xem chức năng
module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
3: - Đầu tiên chúng tôi nhận và kiểm tra tải lên tệp từ module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
4. - Tiếp theo chúng tôi sử dụng npm install express multer sequelize mysql2 read-excel-file
2 Để đọc tệp Excel trong thư mục tải lên, dữ liệu được trả về dưới dạng module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
6 sẽ được thay đổi thành mảng module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
7. - Sau đó, chúng tôi sử dụng phương thức Sequelize model {
"name": "node-js-upload-download-excel-files",
"version": "1.0.0",
"description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File",
"main": "src/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node js",
"upload",
"import",
"download",
"excel",
"files",
"mysql",
"database"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"multer": "^1.4.2",
"mysql2": "^2.1.0",
"read-excel-file": "^4.0.6",
"sequelize": "^5.21.13"
}
}
6 để lưu mảng module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
7 [ID, tiêu đề, mô tả, xuất bản] vào cơ sở dữ liệu MySQL.– First we get and check file upload from
module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
4.– Next we use
npm install express multer sequelize mysql2 read-excel-file
2 to read Excel file in uploads
folder, the data which is returned as module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
6 will be changed to module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
7 array.– Then we use Sequelize model
{
"name": "node-js-upload-download-excel-files",
"version": "1.0.0",
"description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File",
"main": "src/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node js",
"upload",
"import",
"download",
"excel",
"files",
"mysql",
"database"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"multer": "^1.4.2",
"mysql2": "^2.1.0",
"read-excel-file": "^4.0.6",
"sequelize": "^5.21.13"
}
}
6 method to save the module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
7 array [id, title, description, published] to MySQL database.Hàm
const dbConfig = require["../config/db.config.js"];
const Sequelize = require["sequelize"];
const sequelize = new Sequelize[dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
}];
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.tutorials = require["./tutorial.model.js"][sequelize, Sequelize];
module.exports = db;
0 sử dụng phương thức {
"name": "node-js-upload-download-excel-files",
"version": "1.0.0",
"description": "Node.js Upload/Import Excel files to MySQL Database and download Excel File",
"main": "src/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node js",
"upload",
"import",
"download",
"excel",
"files",
"mysql",
"database"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"multer": "^1.4.2",
"mysql2": "^2.1.0",
"read-excel-file": "^4.0.6",
"sequelize": "^5.21.13"
}
}
5 để trả về tất cả các hướng dẫn được lưu trữ trong bảng hướng dẫn cơ sở dữ liệu.tutorials table.Xác định các tuyến đường để tải lên tệp excel
Khi khách hàng gửi yêu cầu cho điểm cuối bằng yêu cầu HTTP [đăng tệp Excel, nhận hướng dẫn], chúng tôi cần xác định cách máy chủ sẽ phản hồi bằng cách thiết lập các tuyến đường.
Đây là những tuyến đường của chúng tôi:
2: Bàiconst dbConfig = require["../config/db.config.js"]; const Sequelize = require["sequelize"]; const sequelize = new Sequelize[dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, { host: dbConfig.HOST, dialect: dbConfig.dialect, operatorsAliases: false, pool: { max: dbConfig.pool.max, min: dbConfig.pool.min, acquire: dbConfig.pool.acquire, idle: dbConfig.pool.idle } }]; const db = {}; db.Sequelize = Sequelize; db.sequelize = sequelize; db.tutorials = require["./tutorial.model.js"][sequelize, Sequelize]; module.exports = db;
3: Nhậnconst dbConfig = require["../config/db.config.js"]; const Sequelize = require["sequelize"]; const sequelize = new Sequelize[dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, { host: dbConfig.HOST, dialect: dbConfig.dialect, operatorsAliases: false, pool: { max: dbConfig.pool.max, min: dbConfig.pool.min, acquire: dbConfig.pool.acquire, idle: dbConfig.pool.idle } }]; const db = {}; db.Sequelize = Sequelize; db.sequelize = sequelize; db.tutorials = require["./tutorial.model.js"][sequelize, Sequelize]; module.exports = db;
Tạo một hướng dẫn.Routes.js bên trong thư mục các tuyến đường có nội dung như thế này:
const express = require["express"];
const router = express.Router[];
const excelController = require["../controllers/tutorials/excel.controller"];
const upload = require["../middlewares/upload"];
let routes = [app] => {
router.post["/upload", upload.single["file"], excelController.upload];
router.get["/tutorials", excelController.getTutorials];
app.use["/api/excel", router];
};
module.exports = routes;
Bạn có thể thấy rằng chúng tôi sử dụng bộ điều khiển từ
const dbConfig = require["../config/db.config.js"];
const Sequelize = require["sequelize"];
const sequelize = new Sequelize[dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
}];
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.tutorials = require["./tutorial.model.js"][sequelize, Sequelize];
module.exports = db;
4.Tạo máy chủ ứng dụng Express
Cuối cùng, chúng tôi tạo một máy chủ tốc hành.
server.js
"Content-disposition" : "attachment; filename=[yourFileName]"
"Content-Type" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
0Trong mã ở trên, chúng tôi khởi tạo bộ định tuyến Express và gọi phương thức Sequelize
const dbConfig = require["../config/db.config.js"];
const Sequelize = require["sequelize"];
const sequelize = new Sequelize[dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
}];
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.tutorials = require["./tutorial.model.js"][sequelize, Sequelize];
module.exports = db;
5."Content-disposition" : "attachment; filename=[yourFileName]"
"Content-Type" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
1Trong phát triển, bạn có thể cần phải bỏ các bảng hiện có và cơ sở dữ liệu đồng bộ hóa lại. Chỉ cần sử dụng
const dbConfig = require["../config/db.config.js"];
const Sequelize = require["sequelize"];
const sequelize = new Sequelize[dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
}];
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.tutorials = require["./tutorial.model.js"][sequelize, Sequelize];
module.exports = db;
6 như mã sau:"Content-disposition" : "attachment; filename=[yourFileName]"
"Content-Type" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
2Chạy & Kiểm tra
Đầu tiên chúng ta cần tạo thư mục tải lên với đường dẫn
const dbConfig = require["../config/db.config.js"];
const Sequelize = require["sequelize"];
const sequelize = new Sequelize[dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
}];
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.tutorials = require["./tutorial.model.js"][sequelize, Sequelize];
module.exports = db;
7. Trên thư mục gốc dự án, hãy chạy lệnh này: const dbConfig = require["../config/db.config.js"];
const Sequelize = require["sequelize"];
const sequelize = new Sequelize[dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
}];
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.tutorials = require["./tutorial.model.js"][sequelize, Sequelize];
module.exports = db;
8uploads folder with the path const dbConfig = require["../config/db.config.js"];
const Sequelize = require["sequelize"];
const sequelize = new Sequelize[dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
}];
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.tutorials = require["./tutorial.model.js"][sequelize, Sequelize];
module.exports = db;
7.On the project root folder, run this command:
const dbConfig = require["../config/db.config.js"];
const Sequelize = require["sequelize"];
const sequelize = new Sequelize[dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
}];
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.tutorials = require["./tutorial.model.js"][sequelize, Sequelize];
module.exports = db;
8Hãy để sử dụng Postman để thực hiện yêu cầu bài đăng HTTP với tệp Excel.Postman to make HTTP POST request with an Excel file.
Kết quả trong bảng hướng dẫn MySQL:tutorials table:
Sự kết luận
Hôm nay, chúng tôi đã xây dựng API CRUD REST bằng Node.js Express để tải lên và nhập dữ liệu từ tệp Excel sang bảng cơ sở dữ liệu MySQL.
Chúng tôi cũng thấy cách sử dụng
npm install express multer sequelize mysql2 read-excel-file
2 để đọc dữ liệu từ tệp Excel, module.exports = [sequelize, Sequelize] => {
const Tutorial = sequelize.define["tutorial", {
title: {
type: Sequelize.STRING
},
description: {
type: Sequelize.STRING
},
published: {
type: Sequelize.BOOLEAN
}
}];
return Tutorial;
};
0 để truy xuất các mục trong bảng cơ sở dữ liệu mà không cần mã Boilerplate.Nếu bạn muốn thêm phân trang trong khi nhận dữ liệu từ bảng MySQL, bạn có thể tìm thấy hướng dẫn tại: Sên máy chủ trong Node.js với phần tiếp theo & MySQL
Server side Pagination in Node.js with Sequelize & MySQL
Để tải xuống tệp Excel: Node.js Tải xuống ví dụ về tệp Excel với Exceljs
Node.js Download Excel file example with exceljs
Hoặc làm việc với tệp CSV thay thế: Node.js: Tải dữ liệu tệp CSV vào cơ sở dữ liệu với Express
Node.js: Upload CSV file data into Database with Express
Học hỏi! Hẹn gặp lại.
Đọc thêm
- //www.npmjs.com/package/express
- //www.npmjs.com/package/multer
- //sequelize.org/v3/api/model/
- read-excel-file
- Node.js REST API với Express & MySQL - Node.js REST API với Express & MySQL [bao gồm cả phần tiếp theo]
– Node.js Rest APIs with Express & MySQL [including Sequelize]
FullStack: - Vue.js + Node.js + Express + MySQL Ví dụ - Vue.js + Node.js + Express + MongoDB Ví dụ - Angular 8 + Node.js Express + MySQL Ví dụ - Angular 10 + Node.js Express + MySQL Ví dụ - Angular 11 + Node.js Express + MySQL Ví dụ - Angular 12 + Node.js Express + MySQL Ví dụ - React + Node.js + Express + MySQL Ví dụ
– Vue.js + Node.js + Express + MySQL example
–
Vue.js + Node.js + Express + MongoDB example
– Angular 8 + Node.js Express + MySQL example
– Angular 10 + Node.js Express + MySQL example
– Angular 11 +
Node.js Express + MySQL example
– Angular 12 + Node.js Express + MySQL example
– React + Node.js + Express + MySQL example
Bảo mật: Node.js - Xác thực và ủy quyền JWT Triển khai: - Triển khai/lưu trữ ứng dụng Node.js trên cơ sở dữ liệu MySQL - DOCKERIZE NODE.JS Express và MySQL ví dụ - Docker Compose
Deployment:
–
Deploying/Hosting Node.js app on Heroku with MySQL database
– Dockerize Node.js Express and MySQL example – Docker Compose
Node.js & MYSQL Hiệp hội:-Ví dụ về mối quan hệ một-nhiều
– One-to-Many Relationship example
–
Many-to-Many Relationship example
Mã nguồn
Bạn có thể tìm thấy mã nguồn đầy đủ cho ví dụ này trên GitHub.