【问题标题】:How do I display images in an express route如何在快速路线中显示图像
【发布时间】:2019-01-15 17:12:08
【问题描述】:

我有一些图像存储在 mongodb 数据库中,我希望能够通过转到 localhost:3003/api/image/filename 一次显示其中一个图像。

现在我有两条路由,一条将所有图像显示为 JSON (localhost:3003/api/files),另一条使用文件名将单个图像显示为 JSON (localhost:3003/api/files/:filename)。

这就是我的图像在 mongodb 集合 fs.files 中的样子

[{
    "_id": "5b6a203a54c9ff33fccdd107",
    "length": 52673,
    "chunkSize": 261120,
    "uploadDate": "2018-08-07T22:42:02.908Z",
    "filename": "9b0cecbccb287d284f116715799fc4be.jpg",
    "md5": "ad4350fc16c7e60054eafa0912620f9b",
    "contentType": "image/jpeg"
},
{
    "_id": "5b6addc9247c341f5861c02e",
    "length": 1674791,
    "chunkSize": 261120,
    "uploadDate": "2018-08-08T12:10:52.976Z",
    "filename": "c2c5015081fba1695429872b6e978772.jpg",
    "md5": "d03ae745631580df00bd0e84bbd1ff87",
    "contentType": "image/jpeg"
},
{
    "_id": "5b6addd1247c341f5861c036",
    "length": 20423,
    "chunkSize": 261120,
    "uploadDate": "2018-08-08T12:10:57.737Z",
    "filename": "97a4377b042cacd2fae5a87aab5849e2.jpg",
    "md5": "7161cc94b3cd73f6837891b58b80f4dc",
    "contentType": "image/jpeg"
}]

我不确定是否应该添加它,但这是 mongo 连接:

MongoClient.connect('mongodb://localhost:27017',{ useNewUrlParser: true }, function(error, client) {
  if (error) {
    console.error('Failed to connect to the database!');
    console.log(error);
  } else {
    console.log('Successfully connected to the database!');
    db = client.db('chattdb');
    gfscollection = db.collection('fs.files'); 
  }
});

那么如何创建一个app.get 路由来返回文件名指定的图像?

编辑:

上传图片到mongodb:

    const storage = new GridFsStorage({
  url: 'mongodb://localhost:27017/chattdb',
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(16, (err, buf) => {
        if (err) {
          return reject(err);
        }
        const filename = buf.toString('hex') + path.extname(file.originalname);
        const fileInfo = {
          filename: filename
        };
        resolve(fileInfo);
      });
    });
  }
});
const upload = multer({ storage });

app.post('/api/files', upload.single('file'), (req, res) => { 
  res.json({file: req.file});  
});

检索图像:

    app.get('/api/image/:filename', (req, res) => {
  gfscollection.findOne({filename: req.params.filename}, (err, image) => {
    if (!image || image.length === 0) {
      return res.status(404).json({
        err: 'No file exist'
      });
    }
    res.set('Content-Type', 'image/jpg'); 
    res.send(image);
  });
});

用于从前端上传的 React 组件:

    class FileUpload extends React.Component{
  constructor(props){
    super()
  this.state = {
    File: null
  };
  this.onFileChange = this.onFileChange.bind(this);
}
  onFileChange(event) {
    this.setState({ File: event.target.value });
  }

  fileUpload(){

      var fd = new FormData();    
      fd.append('file', this.refs.file.files[0]);

    fetch('http://localhost:3003/api/files', {
      method: 'POST',
      body: fd 
      }).then((response) => response.json())
      .then((result) => {
        console.log(result);
      })
  }

  render(){
    return <div className="file-input">
      <form ref="uploadForm" className="uploader" encType="multipart/form-data" >
      <input ref="file" className="file-input-field" name="file" type="file" onChange={this.onFileChange}></input>
      <button className="send-btn" onClick={this.fileUpload.bind(this)}>Upload</button>
      </form>
    </div>
  }

};

【问题讨论】:

  • 如果我理解得很好,你想要的是用一个文件来回应,对吗?
  • 是的,没错
  • 我的回答对你有帮助吗?
  • 我仍在使用它,我有一个读取流,但是当我使用路由时,我的服务器崩溃了,我收到一个错误 cannot read property 'readPreference' of undefined.. 你的回答让我朝着正确的方向前进
  • 如果您可以将其标记为已接受的答案,我将不胜感激。

标签: node.js mongodb express gridfs


【解决方案1】:

您需要使用res.send() 传递存储在Mongo 中的Buffer

例如:

    res.contentType(doc.contentType);
    res.send(doc.data);

编辑:

看来您需要使用gridfs-stream 来获取文件数据并通过响应管道进行流式传输。

也许这可以帮助你:

Storing and Retrieving files from MongoDB using MEAN stack and GridFS

【讨论】:

  • 我确实得到了使用此路线的响应,但不是图像,而是黑屏,中间有一个白框。如果我检查白框,我会看到 img 标签已将 src 设置为图像路径
  • 你能分享一下你用来保存到Mongo和从Mongo检索图像的代码吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多