Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
919 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...