FormData()是发送输入字段的值,而不是将文件从React发送到Express Server?

发布于 2025-01-17 11:58:25 字数 2952 浏览 0 评论 0原文

我正在使用React,并尝试将表单输入以及图像文件发送到同一时间。我尝试通过将这些输入数据和文件附加到FormData()并通过Axios Post Request将其发送到后端来尝试,但是问题是:用户给出的表单输入非常适合表示服务器,但在后端

中不确定文件。我的JSX

<form onSubmit={sendData}>
        <input value={data.productName} onChange={handleChange} type="text" name="productName" />
        <input value={data.productfeatures} onChange={handleChange} type="text" name="productfeatures" />

        <input onChange={imgChnage} type="file" name="test_files" />
        <button>Submit</button>
</form>

我处理输入的功能

const [data, setData] = useState({
    productName: "",
    productfeatures: "",
  })
  const { productName, productfeatures } = data;
  const [imgHolder, setImgHolder] = useState();
  const handleChange = (evt) => {
    const value = evt.target.value;
    setData({
      ...data,
      [evt.target.name]: value
    });
  }
  const imgChnage = (e) => {
    setImgHolder(e.target.files[0]);
  };
  console.log(imgHolder);
  const sendData = async (e) => {
    e.preventDefault();
    const fd = new FormData();
    fd.append('name', productName);
    fd.append('features', productfeatures);
    fd.append('image', imgHolder);
    try {
      await axios
        .post("http://localhost:3001/pnit/v1/api/product", fd)
    } catch (error) {
      console.log(error);
    }

所有组合代码

 import { useState } from "react";
    import axios from "axios";
    function App() {
      const [data, setData] = useState({
        productName: "",
        productfeatures: "",
      })

      const { productName, productfeatures } = data;
      const [imgHolder, setImgHolder] = useState();

      const handleChange = (evt) => {
        const value = evt.target.value;
        setData({
          ...data,
          [evt.target.name]: value
        });
      }


      const imgChnage = (e) => {
        setImgHolder(e.target.files[0]);
      };
      
      const sendData = async (e) => {
        e.preventDefault();
        const fd = new FormData();
        fd.append('name', productName);
        fd.append('features', productfeatures);
        fd.append('image', imgHolder);
        try {
          await axios
            .post("http://localhost:3001/pnit/v1/api/product", fd)
        } catch (error) {
          console.log(error);
        }
    
      }
    
      return (
        <>
          <form onSubmit={sendData}>
        <input value={data.productName} onChange={handleChange} type="text" name="productName" />
        <input value={data.productfeatures} onChange={handleChange} type="text" name="productfeatures" />

        <input onChange={imgChnage} type="file" name="test_files" />
        <button>Submit</button>
        </form> 
        </>
      );
    }
    
    export default App;

I am using React and trying to send the form Input as well as a image file to a express server at a same time. I tried by appending these inputs data and file to the formData() and sending it to backend through axios post request, but the problem is : The form input given by user is perfectly going to express server but file is undefined in backend

My JSX

<form onSubmit={sendData}>
        <input value={data.productName} onChange={handleChange} type="text" name="productName" />
        <input value={data.productfeatures} onChange={handleChange} type="text" name="productfeatures" />

        <input onChange={imgChnage} type="file" name="test_files" />
        <button>Submit</button>
</form>

My function to handle input

const [data, setData] = useState({
    productName: "",
    productfeatures: "",
  })
  const { productName, productfeatures } = data;
  const [imgHolder, setImgHolder] = useState();
  const handleChange = (evt) => {
    const value = evt.target.value;
    setData({
      ...data,
      [evt.target.name]: value
    });
  }
  const imgChnage = (e) => {
    setImgHolder(e.target.files[0]);
  };
  console.log(imgHolder);
  const sendData = async (e) => {
    e.preventDefault();
    const fd = new FormData();
    fd.append('name', productName);
    fd.append('features', productfeatures);
    fd.append('image', imgHolder);
    try {
      await axios
        .post("http://localhost:3001/pnit/v1/api/product", fd)
    } catch (error) {
      console.log(error);
    }

All combined code

 import { useState } from "react";
    import axios from "axios";
    function App() {
      const [data, setData] = useState({
        productName: "",
        productfeatures: "",
      })

      const { productName, productfeatures } = data;
      const [imgHolder, setImgHolder] = useState();

      const handleChange = (evt) => {
        const value = evt.target.value;
        setData({
          ...data,
          [evt.target.name]: value
        });
      }


      const imgChnage = (e) => {
        setImgHolder(e.target.files[0]);
      };
      
      const sendData = async (e) => {
        e.preventDefault();
        const fd = new FormData();
        fd.append('name', productName);
        fd.append('features', productfeatures);
        fd.append('image', imgHolder);
        try {
          await axios
            .post("http://localhost:3001/pnit/v1/api/product", fd)
        } catch (error) {
          console.log(error);
        }
    
      }
    
      return (
        <>
          <form onSubmit={sendData}>
        <input value={data.productName} onChange={handleChange} type="text" name="productName" />
        <input value={data.productfeatures} onChange={handleChange} type="text" name="productfeatures" />

        <input onChange={imgChnage} type="file" name="test_files" />
        <button>Submit</button>
        </form> 
        </>
      );
    }
    
    export default App;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱的十字路口 2025-01-24 11:58:25

开发者您好,问题已解决!!

解决问题的步骤:

  1. 通过命令npm iexpress-fileupload在服务器内安装名为express-fileupload的依赖项。

  2. 在服务器主文件中导入express-fileupload

  3. 最后,调用中间件 app.use(fileupload());

为什么会出现问题!:

因为,默认情况下 req.files未定义,但在服务器上调用中间件,它解析 req.files 并显示从前端发送的文件。

Hello developers, the problem is solved !!

Steps to solve a problem :

  1. install the dependency called express-fileupload inside server by the command npm i express-fileupload.

  2. import the express-fileupload at the main file of server.

  3. And finally, call the middleware app.use(fileupload());

Why the problem occured !:

Because, by default the req.files is undefined but calling the middleware at server, it parse the req.files and shows up the files sent from frontend.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文