首页 > 解决方案 > 如何在 react 和 node.js 中将数据从客户端发送到服务器?

问题描述

我正在尝试制作一个功能,让用户从前端上传他们的个人资料图像并将图像发送回服务器。我该怎么做?

我正在使用 multer 来执行此功能。

这是我来自服务器路由的代码库:

router.post('/upload', upload.single('upload'), async (req, res) => {
  try {
    const incident = await incident.findById(req.body.id);
    incident.image = req.file.buffer;
    incident.save();
    res.send();
  } catch (e) {
    res.status(400).send(e);
  }
}, (error, req, res, next) => {
  res.status(400).send({ error: error.message });
});

这是我前端的 UserProfile.js:

const UserProfile = (serverUserData) => {
  const appState = useContext(GlobalContext);
  const { currentUser } = appState;
  const { email, picture, name } = currentUser;
  const [isVerified, setIsVerified] = useState(false);

  const checkVerificationData = () => {
    axios.get("/api/v1/profiles/profile").then((res) => {
      const { data } = res;   
      if (data.verifiedDT) {
        setIsVerified(data.verifiedDT);
      }
    });
  };

  useEffect(() => {
    checkVerificationData();
  }, [isVerified]);


    // Upload user avatar function
    const [imageSelected, setImageSelected] = useState("");

    const uploadImage = () => {
      const formData = new FormData();
      formData.append("file", imageSelected);
      formData.append("upload_preset", "teammateme");
  
      axios.post("http://localhost:8080/upload/", formData)
        .then((response) => {
          if (response.status === 200) {
            checkVerificationData();
            currentUser.picture = response.data.url;
          }
        });
    };

这是出现用户个人资料图像的 UserCard.js:

 {picture ? (
    <div>
      <Avatar
        src={picture}
        alt="Avatar"
        className="avatar--profile_image"
      />  
      <input
        type="file"
        onChange={(event) => {
          onSelectedImage(event.target.files[0]);
        }}  
      />  
      <button onClick={uploadImage}>Submit</button>
    </div>
  ) : (
    <AccountCircleIcon className="avatar--profile_image" />
  )}

标签: node.jsreactjsmulter

解决方案


推荐阅读