如何在快速路线中显示图像

时间:2018-08-08 12:23:10

标签: 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);
  });
});

用于从前端上传的反应组件:

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

};

1 个答案:

答案 0 :(得分:0)

您需要使用<http-firewall ref="customStrictHttpFirewall"/> 传递存储在Mongo中的res.send()

例如:

Buffer

编辑:

似乎您需要使用 res.contentType(doc.contentType); res.send(doc.data); 来获取文件数据并通过响应管道进行流传输。

也许这可以帮助您:

Storing and Retrieving files from MongoDB using MEAN stack and GridFS