Hướng dẫn store image in mongodb - lưu trữ hình ảnh trong mongodb

Sử dụng ExpressJS, Mongoose và Multer

Hình ảnh đã trở thành một phần quan trọng của Internet. Nó không chỉ là các ứng dụng web cần hình ảnh, phương tiện truyền thông xã hội đã đảm bảo rằng người dùng không chỉ tiêu thụ dữ liệu mà còn tạo ra và chia sẻ chúng. Các ứng dụng như WhatsApp, Telegram và Discord cũng hỗ trợ chia sẻ tài liệu. Vì vậy, là một nhà phát triển phụ trợ, việc xử lý hình ảnh và lưu trữ chúng trên cơ sở dữ liệu là phải. Đối với hướng dẫn này, tôi cho rằng bạn khá giỏi với ExpressJS và có thể sử dụng Mongoose, hoặc ít nhất là biết cách sử dụng trình điều khiển gốc MongoDB cho NodeJS. Tôi cũng cho rằng máy chủ Express của bạn đã được thiết lập với Mongoose hoặc bạn đang sử dụng trình điều khiển MongoDB gốc cho NodeJS

Mẫu mã hóa

Khi thực hiện yêu cầu POST, bạn cần mã hóa dữ liệu được truyền theo được hỗ trợ để nó có thể dễ dàng phân tích cú pháp. Các biểu mẫu HTML cung cấp ba phương pháp mã hóa:

  • Ứng dụng/X-www-form-urlencoded: Chế độ mã hóa mặc định. Một chuỗi dài các giá trị tên được tạo, trong đó mỗi cặp tên và cặp giá trị được phân tách bằng một = và mỗi cặp được phân tách bằng một & để nó có thể được phân tích bởi máy chủ.: The default mode of encoding. A long string of name-values is created, where each name and value pair is separated by an =, and each pair is separated by an & so that it can be parsed by the server.
  • Multipart/Form-Data: Mã hóa này được sử dụng khi cần phải tải lên các tệp lên máy chủ.: This encoding is used when there is a need for files to be uploaded to the server.
  • Văn bản/Đồng bằng: Chúng đã được giới thiệu như một phần của đặc tả HTML 5 và không được sử dụng rộng rãi nói chung.: They have been introduced as a part of the HTML 5 specification, and are not used widely in general.

Tại sao xử lý hình ảnh là khác nhau trên Express?

Khi bạn gửi dữ liệu biểu mẫu đến phần phụ trợ Express, Express được trang bị xử lý các mã hóa application/x-www-form-urlencoded và ____8, nó không thể xử lý mã hóa multipart/form-data, chủ yếu được sử dụng để tải lên các tệp. Đây là nơi Multer đến. Một phần mềm trung gian của Node.js sẽ xử lý các biểu mẫu được mã hóa nhiều phần cho chúng tôi.

Thiết lập lược đồ của bạn

Bạn cần xác định lược đồ

// upload.js
const express = require('express')
const multer = require('multer')
//importing mongoose schema file
const Upload = require("../models/Upload");
const app = express()
//setting options for multer
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
0 cho bộ sưu tập nơi bạn sẽ lưu trữ hình ảnh của mình. Nếu bạn đang sử dụng trình điều khiển MongoDB bản địa, bạn có thể bỏ qua phần này.

// Upload.js
const mongoose = require("mongoose");

const UploadSchema = new mongoose.Schema({
fileName: {
type: String,
required: true,
},
file: {
data: Buffer,
contentType: String,
},
uploadTime: {
type: Date,
default: Date.now,
},
});

module.exports = Upload = mongoose.model("upload", UploadSchema);

Trong lược đồ trên, khối

// upload.js
const express = require('express')
const multer = require('multer')
//importing mongoose schema file
const Upload = require("../models/Upload");
const app = express()
//setting options for multer
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
1 là trường quan trọng nhất, phần còn lại có thể được bỏ qua một cách thuận tiện để phù hợp với yêu cầu của bạn.

Thiết lập Multer

Cài đặt Multer cho ứng dụng của bạn:

Sử dụng NPM:

// upload.js
const express = require('express')
const multer = require('multer')
//importing mongoose schema file
const Upload = require("../models/Upload");
const app = express()
//setting options for multer
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
2

Sử dụng sợi:

// upload.js
const express = require('express')
const multer = require('multer')
//importing mongoose schema file
const Upload = require("../models/Upload");
const app = express()
//setting options for multer
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
3

Bây giờ, hãy để tạo ra một tuyến đường sẽ xử lý tải lên tệp. Nhưng trước đó, hãy để ứng dụng cho phép ứng dụng của chúng tôi sử dụng Multer trong

// upload.js
const express = require('express')
const multer = require('multer')
//importing mongoose schema file
const Upload = require("../models/Upload");
const app = express()
//setting options for multer
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
4.

// upload.js
const express = require('express')
const multer = require('multer')
//importing mongoose schema file
const Upload = require("../models/Upload");
const app = express()
//setting options for multer
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

Đoạn trích này đảm bảo rằng tệp được phân tích cú pháp và lưu trữ trong bộ nhớ. CẢNH BÁO: Đảm bảo rằng bạn thực hiện các bước để đảm bảo rằng tệp được tải lên là rất lớn, nếu không bạn có thể nhìn vào mối đe dọa từ chối dịch vụ. Có một số tùy chọn mà bạn có thể sử dụng trong Multer. Hãy xem chúng ở đây.WARNING: Make sure that you take steps to make sure that the file being uploaded isn’t huge, or else you could be looking at a Denial-of-service threat. There are some options that you can use in multer. Take a look at them here.

Sử dụng phần mềm trung gian Multer trong tuyến đường của bạn

Bây giờ bạn đã thiết lập Multer thành công, đã đến lúc sử dụng nó như một phần mềm trung gian trong các yêu cầu của bạn.

app.post("/upload", upload.single("file"), async (req, res) => {
// req.file can be used to access all file properties
try {
//check if the request has an image or not
if (!req.file) {
res.json({
success: false,
message: "You must provide at least 1 file"
});
} else {
let imageUploadObject = {
file: {
data: req.file.buffer,
contentType: req.file.mimetype
},
fileName: req.body.fileName
};
const uploadObject = new Upload(imageUploadObject);
// saving the object into the database
const uploadProcess = await uploadObject.save();
}
} catch (error) {
console.error(error);
res.status(500).send("Server Error");
}
});

Bạn cũng có thể sử dụng

// upload.js
const express = require('express')
const multer = require('multer')
//importing mongoose schema file
const Upload = require("../models/Upload");
const app = express()
//setting options for multer
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
5 thay vì
// upload.js
const express = require('express')
const multer = require('multer')
//importing mongoose schema file
const Upload = require("../models/Upload");
const app = express()
//setting options for multer
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
6 nếu bạn đang mong đợi nhận được nhiều hơn một tệp từ phía trước. Thêm về điều đó ở đây.

Giải thích mã

Phần mềm trung gian

// upload.js
const express = require('express')
const multer = require('multer')
//importing mongoose schema file
const Upload = require("../models/Upload");
const app = express()
//setting options for multer
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
7 được sử dụng để nói với máy chủ rằng chỉ có một tệp được mong đợi từ trình duyệt. Đối số bên trong
// upload.js
const express = require('express')
const multer = require('multer')
//importing mongoose schema file
const Upload = require("../models/Upload");
const app = express()
//setting options for multer
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
6 cho biết tên của trường tệp ở dạng HTML. Sử dụng phần mềm trung gian này cho phép chúng tôi sử dụng
// upload.js
const express = require('express')
const multer = require('multer')
//importing mongoose schema file
const Upload = require("../models/Upload");
const app = express()
//setting options for multer
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
9 bên trong định nghĩa tuyến đường để truy cập vào tệp đã nhận được. Chúng tôi đã sử dụng
app.post("/upload", upload.single("file"), async (req, res) => {
// req.file can be used to access all file properties
try {
//check if the request has an image or not
if (!req.file) {
res.json({
success: false,
message: "You must provide at least 1 file"
});
} else {
let imageUploadObject = {
file: {
data: req.file.buffer,
contentType: req.file.mimetype
},
fileName: req.body.fileName
};
const uploadObject = new Upload(imageUploadObject);
// saving the object into the database
const uploadProcess = await uploadObject.save();
}
} catch (error) {
console.error(error);
res.status(500).send("Server Error");
}
});
0 và
app.post("/upload", upload.single("file"), async (req, res) => {
// req.file can be used to access all file properties
try {
//check if the request has an image or not
if (!req.file) {
res.json({
success: false,
message: "You must provide at least 1 file"
});
} else {
let imageUploadObject = {
file: {
data: req.file.buffer,
contentType: req.file.mimetype
},
fileName: req.body.fileName
};
const uploadObject = new Upload(imageUploadObject);
// saving the object into the database
const uploadProcess = await uploadObject.save();
}
} catch (error) {
console.error(error);
res.status(500).send("Server Error");
}
});
1 để lưu tệp trên cơ sở dữ liệu.
app.post("/upload", upload.single("file"), async (req, res) => {
// req.file can be used to access all file properties
try {
//check if the request has an image or not
if (!req.file) {
res.json({
success: false,
message: "You must provide at least 1 file"
});
} else {
let imageUploadObject = {
file: {
data: req.file.buffer,
contentType: req.file.mimetype
},
fileName: req.body.fileName
};
const uploadObject = new Upload(imageUploadObject);
// saving the object into the database
const uploadProcess = await uploadObject.save();
}
} catch (error) {
console.error(error);
res.status(500).send("Server Error");
}
});
2 là dữ liệu nhị phân thô của tệp nhận được và chúng tôi sẽ lưu trữ nó trên cơ sở dữ liệu.
app.post("/upload", upload.single("file"), async (req, res) => {
// req.file can be used to access all file properties
try {
//check if the request has an image or not
if (!req.file) {
res.json({
success: false,
message: "You must provide at least 1 file"
});
} else {
let imageUploadObject = {
file: {
data: req.file.buffer,
contentType: req.file.mimetype
},
fileName: req.body.fileName
};
const uploadObject = new Upload(imageUploadObject);
// saving the object into the database
const uploadProcess = await uploadObject.save();
}
} catch (error) {
console.error(error);
res.status(500).send("Server Error");
}
});
1 cũng rất quan trọng đối với chúng tôi vì nó sẽ cho trình duyệt biết cách phân tích dữ liệu nhị phân thô, tức là cách giải thích dữ liệu như, cho dù đó là hình ảnh PNG hay JPEG, hoặc một cái gì đó khác. Để tìm hiểu những thông tin khác có thể được truy cập từ
// upload.js
const express = require('express')
const multer = require('multer')
//importing mongoose schema file
const Upload = require("../models/Upload");
const app = express()
//setting options for multer
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
9, bấm vào đây. Chúng tôi phải chia đối tượng tệp thành hai thuộc tính, cụ thể là dữ liệu, chứa nhị phân thô và ContentType, chứa mimetype.data, which contains the raw binary, and the contentType, which contains the mimetype.

Gửi dữ liệu từ Frontend

Hãy nhớ rằng, Multer chỉ chấp nhận multipart/form-data cho các tệp. Đó là lý do tại sao chúng ta cần đặt loại mã hóa thành giống nhau trên mặt trận của chúng ta.



Làm thế nào để chuyển đổi nó trở lại một hình ảnh?

Vâng, về cơ bản có hai cách bạn có thể làm điều này. Bạn hoặc chuyển đổi dữ liệu nhị phân thành hình ảnh trên phần phụ trợ và sau đó gửi nó đến mặt trận hoặc bạn gửi dữ liệu nhị phân đến mặt trận và sau đó chuyển đổi nó thành một hình ảnh. Nó hoàn toàn phụ thuộc vào ý thích của bạn và trường hợp sử dụng của bạn. Làm thế nào để làm nó? Vâng, bài viết đó là cho một ngày thứ Hai WebDev khác.