【问题标题】:File upload from form not woking in React从表单上传文件在 React 中不起作用
【发布时间】:2021-11-25 08:27:17
【问题描述】:

文件上传不工作我卡住了。我不知道如何在Values 中附加文件和状态值的formdata() 并将其作为form-data 传递给api

  const [Values, setValues] = useState({});
  const [image, setImage] = useState();

  const changeHandler = (e) => {
    setValues({ ...Values, [e.target.name]: e.target.value });
  };
const onChange = (e) => {
    // let files = files;
    setValues({ ...Values, [e.target.name]: e.target.files[0] });
  };


  const submitValue = (e) => {
    e.preventDefault();
   

    const config = {
      headers: {
        Authorization: `token ` + localStorage.getItem("token"),
        "Content-type": "multipart/form-data",
      },
    };
    axios
      .patch("profile-update/", Values, config)
      .then(() => {
        alert("updated data");
      })
      .catch((error) => {
        alert(JSON.stringify(error.response.data));
      });

    console.log(allValues);
  };
  useEffect(() => {
    const config = {
      headers: {
        Authorization: `token ` + localStorage.getItem("token"),
      },
    };

    axios.get("customer-profile/", config).then((res) => {
      //  console.log(res.data.details);
      setdata(res.data.customer);
      setdetails(res.data.details);
    });
  }, []);
  return (
    <>
      <div style={styles.wrapper}>
                <form className="medical-edit-form" style={styles.form}>
          
          <small style={styles.filehelp1}>
            <span style={styles.fileP1}>
              allergic reaction?
            </span>
            <input
              onChange={changeHandler}
              name="allergic_reaction"
              style={styles.date}
              type="text"
              defaultValue={details.allergic_reaction}
            
            />
          </small>
          <small style={styles.datehelp}>
            Surgery?
            <input
              onChange={changeHandler}
              name="surgery"
              style={styles.date}
              type="text"
              defaultValue={details.surgery}
             
            />
          </small>
          <small style={styles.datehelp}>
             Menstruation Period 
            <input
              onChange={changeHandler}
              name="Menstruation"
              style={styles.date}
              type="number"
              defaultValue={details.Menstruation}
            />
          </small>
          <small style={styles.datehelp}>
            Menstruation
            <input
              name="Menstruation"
              onChange={changeHandler}
              defaultValue={details.Menstruation_date}
              style={styles.date}
              type="date"
            />
          </small>
          <small style={styles.datehelp}>
            Heridity?
            <input
              onChange={changeHandler}
              name="hereditory"
              style={styles.date}
              defaultValue={details.hereditory}
              type="text"
             
            />
          </small>
          <small style={styles.filehelp1}>
            <span style={styles.fileP1}>
              Gynacology
              Specify.
            </span>
            <input
              onChange={changeHandler}
              name="gynacology"
              style={styles.date}
              type="text"
              defaultValue={details.gynacology}
             
            />
          </small>
          <small style={styles.filehelp1}>
            <span style={styles.fileP1}>
               pregnent?
            </span>
            <input
              onChange={changeHandler}
              name="pregnant"
              style={styles.date}
              type="text"
              defaultValue={pregnant}
            
            />
          </small>
          <small style={styles.datehelp}>
            visit doctor?
            <input
              onChange={changeHandler}
              name="doctor_final_visit"
              style={styles.date}
              defaultValue={details.doctor_final_visit}
              type="date"
            />
          </small>
          <small style={styles.filehelp}>
            <span style={styles.fileP}>
              Upload image
            </span>
            <input name="prescription" onChange={onChange} type="file" />
          </small>
          <div>
            <input
              onClick={submitValue}
              style={styles.ebtn}
              type="submit"
              value="update"
            />
          </div>
        </form>
      </div>
    </>
  );
}

没有文件上传表单工作正常我还想将文件上传添加到此代码中,以便我也可以上传文件。

【问题讨论】:

  • 第一个错误是Image已经是JavaScript全局命名空间中声明的构造函数。所以你的州名必须以一个小的“i”开头
  • axios.patch() 只接受三个参数,你传递四个
  • @Phil 我正在尝试附加其中的 2 个参数,但我不知道如何,我知道在将其传递给 api 之前必须附加值和表单数据
  • 如果您说您的表单在没有文件的情况下正确上传,那么您需要检查输入元素,并且在设置状态时只需从 e.target.value 更改为 e.target.files [0]
  • @MDMNauman 可以分享一个非常有帮助的例子

标签: javascript reactjs


【解决方案1】:

我不知道这是否可行,因为我无法根据假设测试写作。

  const [Values, setValues] = useState({});
  const [image, setImage] = useState();

  const changeHandler = (e) => {
    setValues({ ...Values, [e.target.name]: e.target.value });
  };

const FileHandler = (e) => {
    // let files = files;
    setImage(e.target.files[0]);
  };



  const submitValue = (e) => {
    e.preventDefault();

   const formData = new FormData(); 
   formData.append('Image', image);
   setValues({...Values, formData})

    const config = {
      headers: {
        Authorization: `token ` + localStorage.getItem("token"),
        "Content-type": "multipart/form-data",
      },
    };
    axios
      .patch("profile-update/", Values, config)
      .then(() => {
        alert("updated data");
      })
      .catch((error) => {
        alert(JSON.stringify(error.response.data));
      });

    
  };
  useEffect(() => {
    const config = {
      headers: {
        Authorization: `token ` + localStorage.getItem("token"),
      },
    };

    axios.get("customer-profile/", config).then((res) => {
      //  console.log(res.data.details);
      setdata(res.data.customer);
      setdetails(res.data.details);
    });
  }, []);
  return (
    <>
      <div style={styles.wrapper}>
                <form className="medical-edit-form" style={styles.form}>
          
          <small style={styles.filehelp1}>
            <span style={styles.fileP1}>
              allergic reaction?
            </span>
            <input
              onChange={changeHandler}
              name="allergic_reaction"
              style={styles.date}
              type="text"
              defaultValue={details.allergic_reaction}
            
            />
          </small>
          <small style={styles.datehelp}>
            Surgery?
            <input
              onChange={changeHandler}
              name="surgery"
              style={styles.date}
              type="text"
              defaultValue={details.surgery}
             
            />
          </small>
          <small style={styles.datehelp}>
             Menstruation Period 
            <input
              onChange={changeHandler}
              name="Menstruation"
              style={styles.date}
              type="number"
              defaultValue={details.Menstruation}
            />
          </small>
          <small style={styles.datehelp}>
            Menstruation
            <input
              name="Menstruation"
              onChange={changeHandler}
              defaultValue={details.Menstruation_date}
              style={styles.date}
              type="date"
            />
          </small>
          <small style={styles.datehelp}>
            Heridity?
            <input
              onChange={changeHandler}
              name="hereditory"
              style={styles.date}
              defaultValue={details.hereditory}
              type="text"
             
            />
          </small>
          <small style={styles.filehelp1}>
            <span style={styles.fileP1}>
              Gynacology
              Specify.
            </span>
            <input
              onChange={changeHandler}
              name="gynacology"
              style={styles.date}
              type="text"
              defaultValue={details.gynacology}
             
            />
          </small>
          <small style={styles.filehelp1}>
            <span style={styles.fileP1}>
               pregnent?
            </span>
            <input
              onChange={changeHandler}
              name="pregnant"
              style={styles.date}
              type="text"
              defaultValue={pregnant}
            
            />
          </small>
          <small style={styles.datehelp}>
            visit doctor?
            <input
              onChange={changeHandler}
              name="doctor_final_visit"
              style={styles.date}
              defaultValue={details.doctor_final_visit}
              type="date"
            />
          </small>
          <small style={styles.filehelp}>
            <span style={styles.fileP}>
              Upload image
            </span>
            <input name="prescription" onChange={FileHandler} type="file" />
          </small>
          <div>
            <input
              onClick={submitValue}
              style={styles.ebtn}
              type="submit"
              value="update"
            />
          </div>
        </form>
      </div>
    </>
  );
}

【讨论】:

  • 我试过作为你的答案,但是当我点击提交时出现错误detail: "Multipart form parse error - Invalid boundary in multipart: None"@MD M Nauman
  • "Content-type": "multipart/form-data",我认为错误就在这里
猜你喜欢
  • 2012-04-01
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多