簡體   English   中英

我如何在反應中使用 fetch 提交表單數據和文件?

[英]how can i submit form data and file using fetch in react?

起初,任務被設置為從表單發送數據。 問題是通過以下方式解決的:

export let useRequest = () => {
  let request = async (url, method = "Post", body = null, headers = {}) => {
    try {
      if (body) {
        body = JSON.stringify(body);
        headers["Content-Type"] = "application/json";
      }

      let res = await fetch(url, { method, body, headers });
      let data = await res.json();
      return data;
    } catch (e) {
      throw e;
    }
  };

形式:

 <form>
   <input name="name" class="help-input" placeholder="name" type="text" value=""/>
   <input name="email" class="help-input" placeholder="email" type="text" value=""/>
   <textarea name="message" class="help-input"placeholder="message"></textarea> 
   <input name="file" type="file" value="">
   <input name="agree" type="checkbox" value="" checked/>
   <button type="submit" onClick="props.send">send</button>
</form>

表單容器(表單包裝器):

export let HelpBlock = (props) => {
  let { request } = useRequest();
  let reqFromForm = async (values) => {
    let data = await request("/api/message", "POST", props.values);
    console.log(data.message)
  };
  return (
    <>
      <Form send={reqFromForm}></Form>
    </>
  );
};

單擊按鈕后,數據具有以下結構:

{
    name:name,
    email:email,
    message:message,
    file:file
}

在這種情況下,我認為您可以根據內容類型呈現正文:

export let useRequest = () => {
  let request = async (url, method = "Post", body = null, headers = {}, contentType="application/json" ) => {
    try {
      if (body) {
        body = renderBodyFormat(body, contentType);
        headers["Content-Type"] = contentType;  
      }

      let res = await fetch(url, { method, body, headers });
      let data = await res.json();
      return data;
    } catch (e) {
      throw e;
    }
  };
  return { request };
};

const renderBodyFormat = (data, type) => {
 const formats = {
   "application/json": ()=> JSON.stringify(body),
   "multipart/form-data": ()=> {
      const form = new FormData();
      Object.keys(data).forEach(key => form.append(key, data[key]));
      return form;
   }
 } 

 return formats[type]();

}

編輯://使用鈎子:

const Component = ()=> {
 const {request} = useRequest();

 useEffect(()=> {
   const data = {
    //...other props
    file: new File(["file"], "file.txt", { type: "text/plain"});
   }

   request(url, "Post", data, {}, "multipart/form-data")
   .then(()=> {
     //...
   })
 })
}

在這里您可以找到更多信息https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

暫無
暫無

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

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