node.js - 如何在快速 route 显示图像

标签 node.js mongodb express gridfs

我在 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>
  }

};

最佳答案

您需要使用 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

关于node.js - 如何在快速 route 显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51746651/

相关文章:

javascript - 如何在Vue中提交表单,重定向到新路由并传递参数?

java - 使用Java在mongodb中查找祖先

mongodb - 用 Mongoose 保存在 mongoDb 中,保存了意外的元素

node.js - 使用email-template-v2 Nodejs动态内容不显示

javascript - 来源 : 'tok_visa' in Stripe

node.js - 创建一个包含用户信息的jade默认布局

node.js - 如何使用 mongodb 聚合计算数组字段的百分比?

javascript - 我可以将哈巴狗(ex-jade)与 react 框架一起使用吗?

node.js - 方法返回相同的次数

ruby-on-rails - 带有 Mongoid 的 Rails 模块