Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

node.js - Next.js - serving images from GridFS

I'm looking to serve some images I have stored in my GridFS database to my Next.js project. Sometimes the images load in development (sometimes they don't), however they never load in production. I'm using gridfs-stream to serve the images.

On the client side the image is called like this:

<img src={`/api/image?id=${filename}`} />

And on the server it serves the image like this:

import mongoose from 'mongoose';
import nc from 'next-connect';

const Grid = require('gridfs-stream');
const conn = mongoose.createConnection(gridFSURI);

let gfs;
conn.once('open', () => {
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection('files');
});

const handler = nc();

handler.get((req, res) => {
  gfs.files.findOne({ filename: req.query.id }, (err, file) => {
    if (!file || file.length === 0) {
      return res.status(404).json({
        err: 'No file exists'
      });
    } else {
      const readstream = gfs.createReadStream(file.filename);
      readstream.pipe(res);
    }
  });
})

export const config = {
  api: {
    bodyParser: false,
  },
};

export default handler;

Should these images be served through getServerSideProps?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...