从 React 上传图像请求

ale*_*17k 3 api node.js express reactjs

我想要实现的是将包含上传图像文件的请求从客户端(React)发送到服务器端(Express)

这是我在服务器上创建的表单示例,它发送我应该使用 React 发送的数据:

<form method="post" action="post" enctype="multipart/form-data">
  <input type="file" name="image" /><br /><br />
  <button type="submit" name="upload">Upload</button>
</form>
Run Code Online (Sandbox Code Playgroud)

这是上传图像时提交的表单发送的对象:链接

这里是反应组件:

const Component = () => {
  const setImageAction = async (event) => {
    event.preventDefault();

    const data = await fetch("http://localhost:3000/upload/post", {
      method: "post",
      headers: { "Content-Type": "multipart/form-data" },
      body: JSON.stringify({

      }),
    });
    const uploadedImage = await data.json();
    if (uploadedImage) {
      console.log('Successfully uploaded image');
    } else {
      console.log('Error Found');
    }
  };

  return (
    <div className="content">
      <form onSubmit={setImageAction}>
        <input type="file" name="image" />
        <br />
        <br />
        <button type="submit" name="upload">
          Upload
        </button>
      </form>
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,在 React 组件中,主体请求是空的,因为我还没有弄清楚如何检索该文件对象。

预先感谢您的帮助!

编辑

更新如图所示,唯一的区别是将 State 保持为 Hook

这是新的 React 组件代码:

const LandingPage = () => {
  const [picture, setPicture] = useState({});

  const uploadPicture = (e) => {
    setPicture({
      /* contains the preview, if you want to show the picture to the user
           you can access it with this.state.currentPicture
       */
      picturePreview: URL.createObjectURL(e.target.files[0]),
      /* this contains the file we want to send */
      pictureAsFile: e.target.files[0],
    });
  };

  const setImageAction = async (event) => {
    event.preventDefault();

    const formData = new FormData();
    formData.append("file", picture.pictureAsFile);

    console.log(picture.pictureAsFile);

    for (var key of formData.entries()) {
      console.log(key[0] + ", " + key[1]);
    }

    const data = await fetch("http://localhost:3000/upload/post", {
      method: "post",
      headers: { "Content-Type": "multipart/form-data" },
      body: formData,
    });
    const uploadedImage = await data.json();
    if (uploadedImage) {
      console.log("Successfully uploaded image");
    } else {
      console.log("Error Found");
    }
  };

  return (
    <div className="content landing">
      <form onSubmit={setImageAction}>
        <input type="file" name="image" onChange={uploadPicture} />
        <br />
        <br />
        <button type="submit" name="upload">
          Upload
        </button>
      </form>
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

这是我从这些 console.logs 中得到的:链接

如果您想查看,我在codesandbox中创建了一个片段:https://codesandbox.io/s/heuristic-snyder-d67sn ?file=/src/App.js

Dje*_*iss 6

添加此方法来捕获 onChange 事件:

向您的状态添加 2 个属性:picturePreview 和 pictureAsFile

uploadPicture = (e) => {
        this.setState({
            /* contains the preview, if you want to show the picture to the user
               you can access it with this.state.currentPicture
           */
            picturePreview : URL.createObjectURL(e.target.files[0]),
            /* this contains the file we want to send */
            pictureAsFile : e.target.files[0]
        })
    };
Run Code Online (Sandbox Code Playgroud)

现在,在您的 onSubmit 事件中:

setImageAction = () => {
        const formData = new FormData();
        formData.append(
            "file",
            this.state.pictureAsFile
        );
        // do your post request

    };
Run Code Online (Sandbox Code Playgroud)

当然不要将 uploadPicture 方法添加到您的输入中:

 <input type="file" name="image" onChange={this.uploadPicture}/>
Run Code Online (Sandbox Code Playgroud)

编辑

显示您的 formData :

for (var key of formData.entries()) 
{
    console.log(key[0] + ', ' + key[1])
}
Run Code Online (Sandbox Code Playgroud)