【问题标题】:How to display all images from gridfs如何显示来自gridfs的所有图像
【发布时间】:2017-02-11 21:21:21
【问题描述】:

我在想应该有一个fs.files.findAll(),这样我就可以获取所有文件名并将其显示在页面上。现在我一次只能找到一个,我可以展示它们。我想要一个包含数据库中所有图像的索引页。

const mongoose = require("mongoose");
const Grid = require("gridfs-stream");
const fs = require("fs");
const express = require("express");
const app = express("/")
mongoose.connect("mongodb://localhost/newDb");
const conn = mongoose.connection;

app.set("view engine", "ejs"); // set the view engine
app.use(express.static("public"));

const uploadImages = require("./uploadImages");
const getAllImages = require("./getAllImages");



console.log(mongoose.connection.readyState);

app.get("/:img", (req, res) => {
    getAllImages(conn, req.params.img, res)
})

app.get("/", (req, res) => {
    //render all images on page
    //how do I find how many images are in the DB
    //and to get the file names to pass to ejs
    //so I could do forloop to get // img src "/image1.jpg"
})

app.listen(3000, (err) => {
    console.log("listening on port 3000")
})

在 getAllImages 中

const mongoose = require("mongoose");
const Grid = require("gridfs-stream");
const fs = require("fs")
function getAllImages(conn, img, response){
    const gfs = Grid(mongoose.connection.db, mongoose.mongo);
    const readStream = gfs.createReadStream({
        filename :img
    })
    readStream.on("error" , function(err){
        console.log("An error: ", err);
    })
    readStream.pipe(response);
    // mongoose.connection.db.listCollections( (err, names) => {
    //     console.log(names);
    // })


}
module.exports = getAllImages;

【问题讨论】:

    标签: node.js mongodb express gridfs gridfs-stream


    【解决方案1】:

    我就是这样做的:

    const Schema = mongoose.Schema;
    const Image = mongoose.model("Image",
                new Schema({filename : String, contentType : String, uploadDate : Date}),
                "fs.files"
                );
    

    然后

    app.get("/", (req, res) => {
        Image.find()
            .then((docs) =>{
                var imageNames = docs.map((e) => {
                    return e.filename
                })
                res.render("index", {
                    imageNames
                })
                console.log(docs)
            })
    })
    

    在索引中

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>index</title>
        </head>
        <body>
            <h1>Hello</h1>
            <% imageNames.forEach((e) =>{ %>
                <a href = <%=e %>><%=e.split(".")[0]%></a>
                <img src = "/<%=e%>"> <br>
            <%})%>
        </body>
    </html>
    

    我不想设置猫鼬模式。我听说猫鼬需要那个。还有另一种使用gridf-stream的方法吗?

    【讨论】:

      猜你喜欢
      • 2014-04-08
      • 2017-06-23
      • 1970-01-01
      • 2016-04-27
      • 2012-05-22
      • 2018-05-25
      • 1970-01-01
      • 2014-03-21
      • 1970-01-01
      相关资源
      最近更新 更多