用文本发回img

时间:2017-01-23 23:56:15

标签: node.js mongodb express

我正在撰写简单的博客应用。所以这就像我的帖子架构:

const postSchema = new Schema({
    img: String,
    title: String,
    content: String,
    date: String
  });

我正在将img文件上传到/ uploads文件夹,并将此img的路径保存为每个帖子的字符串。

我想知道如何将此信息发送给客户端。目前,我发送的帖子是JSON。显示文本(标题,内容和日期)没问题,但图像有点令人头疼。

如何以正确的方式做到这一点?

我将在本博客的客户端使用React + Redux。

2 个答案:

答案 0 :(得分:0)

您将需要fs模块来访问文件系统;

 fs = require('fs');

在接收GET请求的回调中:

 var img = fs.readFileSync('./pathToImage');
 res.writeHead(200, {'Content-Type': 'image/gif' });
 res.end(img, 'binary');

答案 1 :(得分:0)

由于您在客户端使用reactredux,您可能只想将服务器端路径转换为客户端 - 边路径。例如,如果您的服务器正在提供以下文件:/path/to/server/public并且您要上传到/path/to/server/public/uploads,则可能只想将该网址发送为/uploads

客户端上,您可以使用相对路径显示您的网址,例如:

import { Component } from 'react'
import { connect } from 'react-redux'

class Post extends Component {
  ...
  render() {
    <div className="post">
      /* Any other rendering you want to do here */
      <img src={this.props.img} />
    </div>
  }
}
export default connect(
  /* Assuming your Redux store has the post stored as `post` */
  state => state.post,
)(Post)