Cách lưu đường dẫn ảnh trong mongodb

Trong hướng dẫn này, tôi sẽ chỉ cho bạn cách tải lên/lưu trữ hình ảnh trong MongoDB bằng Node. js & Express với sự trợ giúp của multer & multer-gridfs-storage

bài viết liên quan
– Cách upload nhiều file trong Node. js
– Tải lên và thay đổi kích thước nhiều hình ảnh trong Node. js bằng Express, Multer, Sharp
- Nút. js Express File Upload Rest API ví dụ (thư mục tĩnh) sử dụng Multer
– Google Cloud Storage với Nút. js. Ví dụ về Tải tệp lên

Thực hành nhiều hơn
- Nút. js, Express & MongoDb. Xây dựng một ví dụ CRUD Rest Api
- Nút. js + MongoDB. Xác thực và ủy quyền người dùng với JWT

triển khai. Docker Soạn. Nút. ví dụ về js Express và MongoDB


nội dung

Tổng quan

nút của chúng tôi. js Ứng dụng sẽ cung cấp API cho

  • tải Tệp/Hình ảnh lên MongoDB
  • nhận danh sách thông tin của Tệp (tên tệp & url)
  • tải xuống Tệp/Hình ảnh từ máy chủ bằng url

Đây là giao diện người dùng

Cách lưu đường dẫn ảnh trong mongodb
Cách lưu đường dẫn ảnh trong mongodb

Bạn có thể sử dụng Máy khách HTTP để tải lên hình ảnh

Cách lưu đường dẫn ảnh trong mongodb
Cách lưu đường dẫn ảnh trong mongodb

Các hình ảnh sẽ được lưu trữ trong 2 bộ sưu tập.

{
  "name": "upload-multiple-images-mongodb",
  "version": "1.0.0",
  "description": "Node.js upload multiple files/images to MongoDB Demo",
  "main": "src/server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node",
    "upload",
    "multiple",
    "files",
    "images",
    "mongodb"
  ],
  "author": "bezkoder",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongodb": "^4.1.3",
    "multer": "^1.4.3",
    "multer-gridfs-storage": "^5.0.2"
  }
}
7 và
{
  "name": "upload-multiple-images-mongodb",
  "version": "1.0.0",
  "description": "Node.js upload multiple files/images to MongoDB Demo",
  "main": "src/server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node",
    "upload",
    "multiple",
    "files",
    "images",
    "mongodb"
  ],
  "author": "bezkoder",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongodb": "^4.1.3",
    "multer": "^1.4.3",
    "multer-gridfs-storage": "^5.0.2"
  }
}
8

Cách lưu đường dẫn ảnh trong mongodb
Cách lưu đường dẫn ảnh trong mongodb

Cách lưu đường dẫn ảnh trong mongodb
Cách lưu đường dẫn ảnh trong mongodb

Nếu chúng tôi nhận được danh sách các tệp hình ảnh, Nút. js Rest Apis sẽ trở lại

Cách lưu đường dẫn ảnh trong mongodb
Cách lưu đường dẫn ảnh trong mongodb

Mỗi mục trong mảng phản hồi có một url mà bạn có thể sử dụng để tải xuống tệp/hình ảnh

Đây là các API sẽ được xuất

MethodsUrlsActionsPOST/uploadupload a File/ImageGET/filesget List of Images (name & url)GET/files/[filename]download a File

nút này. Ứng dụng js hoạt động với
– Máy khách góc 8 / Máy khách góc 10 / Máy khách góc 11 / Góc 12
– Vật liệu góc 12
– Máy khách Vue / Máy khách Vuetify
– Máy khách phản ứng / Máy khách React Hook
– Máy khách giao diện người dùng vật liệu
– Máy khách Axios

Nút. js tải lên/lưu trữ hình ảnh trong MongoDB

Chúng tôi sẽ chỉ cho bạn cách xây dựng Nút này. ứng dụng js từng bước

Cấu trúc dự án

Bây giờ hãy nhìn vào cấu trúc dự án của chúng tôi

Cách lưu đường dẫn ảnh trong mongodb
Cách lưu đường dẫn ảnh trong mongodb

{
  "name": "upload-multiple-images-mongodb",
  "version": "1.0.0",
  "description": "Node.js upload multiple files/images to MongoDB Demo",
  "main": "src/server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node",
    "upload",
    "multiple",
    "files",
    "images",
    "mongodb"
  ],
  "author": "bezkoder",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongodb": "^4.1.3",
    "multer": "^1.4.3",
    "multer-gridfs-storage": "^5.0.2"
  }
}
9. bao gồm cấu hình cho MongoDB và Multer (url, cơ sở dữ liệu, nhóm hình ảnh)


  
    
    
    
    Node.js upload images
    
    
  

  
    

Node.js upload images - bezkoder.com


Thay đổi hình thức để tải lên nhiều hình ảnh

Đối với biểu mẫu, chúng tôi viết thẻ đầu vào với thuộc tính

const express = require("express");
const router = express.Router();
const homeController = require("../controllers/home");
const uploadController = require("../controllers/upload");

let routes = app => {
  router.get("/", homeController.getHome);

  router.post("/upload", uploadController.uploadFiles);
  router.get("/files", uploadController.getListFiles);
  router.get("/files/:name", uploadController.download);

  return app.use("/", router);
};

module.exports = routes;
5 mới như thế này

lượt xem/chỉ mục. html

{
  "name": "upload-multiple-images-mongodb",
  "version": "1.0.0",
  "description": "Node.js upload multiple files/images to MongoDB Demo",
  "main": "src/server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node",
    "upload",
    "multiple",
    "files",
    "images",
    "mongodb"
  ],
  "author": "bezkoder",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongodb": "^4.1.3",
    "multer": "^1.4.3",
    "multer-gridfs-storage": "^5.0.2"
  }
}
1

Sửa đổi phần mềm trung gian để tải lên và lưu trữ hình ảnh

Đối với nhiều hình ảnh, chúng tôi sử dụng một chức năng khác.

const express = require("express");
const router = express.Router();
const homeController = require("../controllers/home");
const uploadController = require("../controllers/upload");

let routes = app => {
  router.get("/", homeController.getHome);

  router.post("/upload", uploadController.uploadFiles);
  router.get("/files", uploadController.getListFiles);
  router.get("/files/:name", uploadController.download);

  return app.use("/", router);
};

module.exports = routes;
6 thay vì
const express = require("express");
const router = express.Router();
const homeController = require("../controllers/home");
const uploadController = require("../controllers/upload");

let routes = app => {
  router.get("/", homeController.getHome);

  router.post("/upload", uploadController.uploadFiles);
  router.get("/files", uploadController.getListFiles);
  router.get("/files/:name", uploadController.download);

  return app.use("/", router);
};

module.exports = routes;
7

phần mềm trung gian/tải lên. js

{
  "name": "upload-multiple-images-mongodb",
  "version": "1.0.0",
  "description": "Node.js upload multiple files/images to MongoDB Demo",
  "main": "src/server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node",
    "upload",
    "multiple",
    "files",
    "images",
    "mongodb"
  ],
  "author": "bezkoder",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongodb": "^4.1.3",
    "multer": "^1.4.3",
    "multer-gridfs-storage": "^5.0.2"
  }
}
2

– Hàm

const express = require("express");
const router = express.Router();
const homeController = require("../controllers/home");
const uploadController = require("../controllers/upload");

let routes = app => {
  router.get("/", homeController.getHome);

  router.post("/upload", uploadController.uploadFiles);
  router.get("/files", uploadController.getListFiles);
  router.get("/files/:name", uploadController.download);

  return app.use("/", router);
};

module.exports = routes;
8 giới hạn số lượng tệp tải lên mỗi lần, tham số đầu tiên là tên của thẻ –
module.exports = {
  url: "mongodb://localhost:27017/",
  database: "bezkoder_files_db",
  imgBucket: "photos",
};
1 (ở chế độ xem html.
const path = require("path");

const home = (req, res) => {
  return res.sendFile(path.join(`${__dirname}/../views/index.html`));
};

module.exports = {
  getHome: home
};
4), tham số thứ hai là số tệp tối đa (
const cors = require("cors");
const express = require("express");
const app = express();
const initRoutes = require("./routes");

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));
app.use(express.urlencoded({ extended: true }));
initRoutes(app);

let port = 8080;
app.listen(port, () => {
  console.log(`Running at localhost:${port}`);
});
1)

Bộ điều khiển để tải lên nhiều hình ảnh

Với bộ điều khiển, chúng tôi cập nhật chức năng

const upload = require("../middleware/upload");
const dbConfig = require("../config/db");

const MongoClient = require("mongodb").MongoClient;
const GridFSBucket = require("mongodb").GridFSBucket;

const url = dbConfig.url;

const baseUrl = "http://localhost:8080/files/";

const mongoClient = new MongoClient(url);

const uploadFiles = async (req, res) => {
  try {
    await upload(req, res);
    console.log(req.file);

    if (req.file == undefined) {
      return res.send({
        message: "You must select a file.",
      });
    }

    return res.send({
      message: "File has been uploaded.",
    });
  } catch (error) {
    console.log(error);

    return res.send({
      message: "Error when trying upload image: ${error}",
    });
  }
};

const getListFiles = async (req, res) => {
  try {
    await mongoClient.connect();

    const database = mongoClient.db(dbConfig.database);
    const images = database.collection(dbConfig.imgBucket + ".files");

    const cursor = images.find({});

    if ((await cursor.count()) === 0) {
      return res.status(500).send({
        message: "No files found!",
      });
    }

    let fileInfos = [];
    await cursor.forEach((doc) => {
      fileInfos.push({
        name: doc.filename,
        url: baseUrl + doc.filename,
      });
    });

    return res.status(200).send(fileInfos);
  } catch (error) {
    return res.status(500).send({
      message: error.message,
    });
  }
};

const download = async (req, res) => {
  try {
    await mongoClient.connect();

    const database = mongoClient.db(dbConfig.database);
    const bucket = new GridFSBucket(database, {
      bucketName: dbConfig.imgBucket,
    });

    let downloadStream = bucket.openDownloadStreamByName(req.params.name);

    downloadStream.on("data", function (data) {
      return res.status(200).write(data);
    });

    downloadStream.on("error", function (err) {
      return res.status(404).send({ message: "Cannot download the Image!" });
    });

    downloadStream.on("end", () => {
      return res.end();
    });
  } catch (error) {
    return res.status(500).send({
      message: error.message,
    });
  }
};

module.exports = {
  uploadFiles,
  getListFiles,
  download,
};
2

bộ điều khiển/tải lên. js

{
  "name": "upload-multiple-images-mongodb",
  "version": "1.0.0",
  "description": "Node.js upload multiple files/images to MongoDB Demo",
  "main": "src/server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node",
    "upload",
    "multiple",
    "files",
    "images",
    "mongodb"
  ],
  "author": "bezkoder",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongodb": "^4.1.3",
    "multer": "^1.4.3",
    "multer-gridfs-storage": "^5.0.2"
  }
}
3

Có một phần bổ sung trong khối

const cors = require("cors");
const express = require("express");
const app = express();
const initRoutes = require("./routes");

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));
app.use(express.urlencoded({ extended: true }));
initRoutes(app);

let port = 8080;
app.listen(port, () => {
  console.log(`Running at localhost:${port}`);
});
3. Chúng tôi kiểm tra xem
const cors = require("cors");
const express = require("express");
const app = express();
const initRoutes = require("./routes");

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));
app.use(express.urlencoded({ extended: true }));
initRoutes(app);

let port = 8080;
app.listen(port, () => {
  console.log(`Running at localhost:${port}`);
});
4 có phải là
const cors = require("cors");
const express = require("express");
const app = express();
const initRoutes = require("./routes");

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));
app.use(express.urlencoded({ extended: true }));
initRoutes(app);

let port = 8080;
app.listen(port, () => {
  console.log(`Running at localhost:${port}`);
});
5 để hiển thị thông báo cho người dùng khi họ cố tải lên hơn 10 hình ảnh/tệp không

Đừng quên thay đổi phương pháp điều khiển trên bộ định tuyến

{
  "name": "upload-multiple-images-mongodb",
  "version": "1.0.0",
  "description": "Node.js upload multiple files/images to MongoDB Demo",
  "main": "src/server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node",
    "upload",
    "multiple",
    "files",
    "images",
    "mongodb"
  ],
  "author": "bezkoder",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongodb": "^4.1.3",
    "multer": "^1.4.3",
    "multer-gridfs-storage": "^5.0.2"
  }
}
4

Chạy & Kiểm tra kết quả

Chạy lệnh.

const express = require("express");
const router = express.Router();
const homeController = require("../controllers/home");
const uploadController = require("../controllers/upload");

let routes = app => {
  router.get("/", homeController.getHome);

  router.post("/upload", uploadController.uploadFiles);
  router.get("/files", uploadController.getListFiles);
  router.get("/files/:name", uploadController.download);

  return app.use("/", router);
};

module.exports = routes;
1

Và giao diện điều khiển hiển thị

Running at localhost:8080

Mở trình duyệt của bạn với url

const express = require("express");
const router = express.Router();
const homeController = require("../controllers/home");
const uploadController = require("../controllers/upload");

let routes = app => {
  router.get("/", homeController.getHome);

  router.post("/upload", uploadController.uploadFiles);
  router.get("/files", uploadController.getListFiles);
  router.get("/files/:name", uploadController.download);

  return app.use("/", router);
};

module.exports = routes;
2, thêm một số hình ảnh như thế này

Cách lưu đường dẫn ảnh trong mongodb
Cách lưu đường dẫn ảnh trong mongodb

Nhấp vào nút Gửi. Nếu những hình ảnh này được tải lên và lưu trữ trong MongoDB thành công, bạn có thể thấy

Cách lưu đường dẫn ảnh trong mongodb
Cách lưu đường dẫn ảnh trong mongodb

Bảng điều khiển hiển thị thông tin của những hình ảnh này

{
  "name": "upload-multiple-images-mongodb",
  "version": "1.0.0",
  "description": "Node.js upload multiple files/images to MongoDB Demo",
  "main": "src/server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node",
    "upload",
    "multiple",
    "files",
    "images",
    "mongodb"
  ],
  "author": "bezkoder",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongodb": "^4.1.3",
    "multer": "^1.4.3",
    "multer-gridfs-storage": "^5.0.2"
  }
}
6

Kiểm tra cơ sở dữ liệu MongoDB
-

const util = require("util");
const multer = require("multer");
const { GridFsStorage } = require("multer-gridfs-storage");
const dbConfig = require("../config/db");

var storage = new GridFsStorage({
  url: dbConfig.url + dbConfig.database,
  options: { useNewUrlParser: true, useUnifiedTopology: true },
  file: (req, file) => {
    const match = ["image/png", "image/jpeg"];

    if (match.indexOf(file.mimetype) === -1) {
      const filename = `${Date.now()}-bezkoder-${file.originalname}`;
      return filename;
    }

    return {
      bucketName: dbConfig.imgBucket,
      filename: `${Date.now()}-bezkoder-${file.originalname}`
    };
  }
});

var uploadFiles = multer({ storage: storage }).single("file");
var uploadFilesMiddleware = util.promisify(uploadFiles);
module.exports = uploadFilesMiddleware;
8 bộ sưu tập

Cách lưu đường dẫn ảnh trong mongodb
Cách lưu đường dẫn ảnh trong mongodb

-

const cors = require("cors");
const express = require("express");
const app = express();
const initRoutes = require("./routes");

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));
app.use(express.urlencoded({ extended: true }));
initRoutes(app);

let port = 8080;
app.listen(port, () => {
  console.log(`Running at localhost:${port}`);
});
9 bộ sưu tập

Cách lưu đường dẫn ảnh trong mongodb
Cách lưu đường dẫn ảnh trong mongodb

Nếu bạn cố gắng tải lên hơn 10 tệp cùng một lúc, bạn có thể thấy lỗi như thế này

Cách lưu đường dẫn ảnh trong mongodb
Cách lưu đường dẫn ảnh trong mongodb

Phần kết luận

Hôm nay chúng ta đã học cách tải lên và lưu trữ một/nhiều hình ảnh trong cơ sở dữ liệu MongoDB bằng cách sử dụng các mô-đun express, multer & multer-gridfs-storage, cách giới hạn số lượng tệp theo cấu hình

Làm cách nào để lưu trữ tệp hình ảnh trong MongoDB?

Cách tải lên/lưu trữ hình ảnh trong MongoDB bằng Node. .
Thiết lập nút. mô-đun js
Tạo Chế độ xem để tải lên hình ảnh
Định cấu hình cơ sở dữ liệu MongoDB
Tạo phần mềm trung gian để tải lên và lưu trữ hình ảnh
Tạo Controller cho view
Tạo Trình điều khiển để tải lên Hình ảnh
Xác định tuyến đường
Tạo máy chủ ứng dụng Express

Có thể lưu trữ hình ảnh trong MongoDB không?

Không, MongoDB không phải là nơi tốt để lưu trữ tệp . Nếu bạn muốn lưu trữ tệp, bạn nên sử dụng các kho lưu trữ như Amazon S3 hoặc Google Could Storage. Cách thực hành tốt là lưu trữ các tệp trong bộ lưu trữ và sau đó chỉ lưu URL của hình ảnh đã tải lên trong MongoDB.

Làm cách nào để lưu trữ tệp phương tiện trong MongoDB?

Trong MongoDB, sử dụng GridFS để lưu trữ tệp lớn hơn 16 MB . Trong một số trường hợp, việc lưu trữ các tệp lớn trong cơ sở dữ liệu MongoDB có thể hiệu quả hơn trên hệ thống tệp cấp hệ thống. Nếu hệ thống tệp của bạn giới hạn số lượng tệp trong một thư mục, bạn có thể sử dụng GridFS để lưu trữ bao nhiêu tệp tùy ý.

Làm cách nào để lưu trữ hình ảnh trong MongoDB bằng nút JS?

Làm theo các bước sau để tải lên và lưu trữ tệp hình ảnh trong MongoDB bằng cách sử dụng nút js. .
Bước 1 – Tạo ứng dụng Node Express js
Bước 2 – Cài đặt các phụ thuộc Multer của cầy mangut phân tích cú pháp cơ thể nhanh
Bước 3 – Kết nối ứng dụng với MongoDB
Bước 4 – Tạo mô hình
Bước 5 – Tạo biểu mẫu đánh dấu HTML tải lên tệp/hình ảnh