簡體   English   中英

如何使用 Multer 將包含圖像和文本的表單輸入數據從 React 前端發送到 Express 后端

[英]How to send a form input data containing both image and text from React front-end to Express backend using Multer

當我測試發送包含從用戶那里抓取的圖像和文本的請求時,當我使用 Postman 時,它會以正確的數據傳遞到后端。 不過,不是來自 React 前端。 請求確實通過了,但是當我從后端 console.log 時, req.body 似乎是空的。 我究竟做錯了什么? 我正在使用 Multer。

//FRONT-END
import React, { useState } from 'react';
import axios from 'axios';

const ListProperty = (props) => {
  const [address, setAddress] = useState('');
  const [file, setFile] = useState(null);
  const [filename, setFilename] = useState('Choose File');

  const handleAddressChange = (evt) => {
    setAddress(evt.target.value);
  };

  const handlePhotoSelect = (evt) => {
    setFile(evt.target.files[0]);
    setFilename(evt.target.files[0].name);
  };

  const handleSubmit = async (evt) => {
    evt.preventDefault();
    const formData = new FormData();
    formData.append('address', address);
    formData.append('upload', file);
    console.log(formData);
    try {
      axios.post('http://localhost:3000/listproperty', {
        headers: { 'Content-Type': 'multipart/form-data' },
        body: formData,
      });
    } catch (err) {
      console.log(err);
    }
  };
  return (
    <div>
      <h2>Property Listing Form</h2>
      <span>Provide property address and Photo</span>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={address}
          onChange={handleAddressChange}
          name={address}
          placeholder="Enter address"
        />
        <br />
        <input type="file" onChange={handlePhotoSelect} />
        <button>Click to list</button>
      </form>
    </div>
  );
};

export default ListProperty;


//BACK-END
const express = require('express');
const PropertyModel = require('../models/propertyModel');
const router = new express.Router();
const UserModel = require('../models/userModel');
const multer = require('multer');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/images');
  },
  filename: function (req, file, cb) {
    const uniqueName = `${Math.random().toString(32).slice(2)}.jpg`;
    req.image = uniqueName;
    cb(null, uniqueName);
  },
});

const upload = multer({ storage });

router.post(
  '/listproperty',
  upload.single('upload'),
  async (req, res) => {
    console.log('hitting Backend router');
    const property = new PropertyModel({
      ...req.body,
      owner: req.user._id,
      photo: req.image,
    });
    await UserModel.findByIdAndUpdate(req.user._id, {
      $push: { properties: property._id },
    });
    try {
      await property.save();
      res.status(200).send(property);
    } catch (err) {
      console.log(err);
      res.status(400).send(err);
    }
  }
);


module.exports = router;

您的 axios 請求不正確。 axios post 請求接受數據作為第二個參數,第三個參數用於選項(標頭等),

axios.post('http://localhost:3000/listproperty', formData, {
  headers: { 
    'Content-Type': 'multipart/form-data' 
  }
});

另一件事是您的請求根本沒有被觸發。 嘗試將輸入類型設置為提交,而不是使用按鈕來觸發表單的 onSubmit 處理程序。

<form onSubmit={handleSubmit}>
        <input
            type="text"
            value={address}
            onChange={handleAddressChange}
            name={address}
            placeholder="Enter address"
        />
        <br />
        <input type="file" onChange={handlePhotoSelect} />
        <input type="submit" value="Submit" />
    </form>

如果您在正文中發送表單數據,則需要使用強大的npm 模塊

您可以使用npm i formidable安裝它,然后在文件頂部要求 formidable

var formidable = require("formidable");
    
router.post(
'/listproperty',
upload.single('upload'),
async (req, res) => {
    
     var form = new formidable.IncomingForm();
      form.multiples = false;
      form.parse(req, async function (err, fields, files) {
    /**now here you can get all files in files and fields with fields
       in your case you have sent
       formData.append('address', address);
       formData.append('upload', file);
       above two data in form
       so you can get your image from files.upload
       and address fields.address **/
    })
})

另外,我建議您使用 Axios 進行 api 調用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM