首页 > 解决方案 > 上传带有其他信息的图像文件(文本)

问题描述

我正在创建可以一起发布一些信息和图像文件的应用程序。我想我在后端成功了,但我不知道如何在前端使用 React。

后端我使用 node.js + multer + mongoDB .. 前端我使用 react.js + ajax ...

当我使用邮递员进行测试时,我未选中标题,并在正文中使用了表单数据并且它起作用了。

我已经尝试过的前端...

class CreateContainer extends Component {
  constructor(){
    super()
    this.state = {
      house : {
        street: '',
        address: '',
        state: '',
        zipcode: '',
        year: '',
        sqft: '',
        productImage: ''
      },
    }
  }

  handleInput = (e) => {
    const updatedChange = {
      ...this.state.house
    }
    updatedChange[e.target.name] = e.target.value;
    this.setState({
      house: updatedChange
    })
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const updatedHouse = {
      ...this.state.house
    }
    this.addHouse(updatedHouse)
    this.setState({
      house : {
        street: '',
        address: '',
        state: '',
        zipcode: '',
        year: '',
        sqft: '',
        productImage: ''
      }
    })
  }

  addHouse = async(updatedHouse) => {
    try{
        const response = await fetch(`${process.env.REACT_APP_API}/api/v1/house`, {
          method: 'POST',
          credentials: 'include',
          body: JSON.stringify(updatedHouse),
          headers: {
            'Content-Type' : 'application/json',
            'Accept': 'application/json',
          }
        });


        if(!response.ok){
          throw Error(response.statusText)
        }

        const parsedCreateHouse = await response.json();

        this.props.history.push('/home');

      } catch(err) {
        console.log('cannot make house');
      }
    }

后端

router.post('/', upload.single('productImage'), (req, res, next) => {
  const userId = req.session.userId
  const product = new House({
    _id: new mongoose.Types.ObjectId(),
    street: req.body.street,
    address: req.body.address,
    state: req.body.state,
    zipcode: req.body.zipcode,
    year: req.body.year,
    sqft: req.body.sqft,
    productImage: req.file.path,
    userId: userId
  });

  product
    .save()
    .then(result => {
      res.status(201).json({
        message: 'handle post route',
        createdProduct: {
            _id: result._id,
            street: result.street,
            address: result.address,
            state: result.state,
            zipcode: result.zipcode,
            year: result.year,
            sqft: result.sqft,
            request: {
              type: 'GET',
              url: 'http://localhost:9000/api/v1/house/' +  result._id
            }
        }
      });
    })
    .catch(err => {
      console.log('error: post request fail');
      res.status(500).json({
        error: err
      })
    });

})

我想像这样创建和存储房屋信息和图片作为一个数据(?),...

{
    "status": 200,
    "data": {
        "_id": "5d388b0cd8129405f01ba3da",
        "address": "jjj",
        "state": "jjj",
        "zipcode": "jjj",
        "year": "jjj",
        "sqft": "jjj",
        "productImage": "public/uploads/2019-07-24T16:45:00.501Zaudrey.png",
        "__v": 0
    }
}

标签: javascriptnode.jsreactjspostmulter

解决方案


推荐阅读