简体   繁体   中英

Sending file to server API using fetch POST method

I'm trying to send .xml file from my PC to a server, but im getting this error: POST https://localhost:44391/api/edit net::ERR_ABORTED 415

File state

const [file, setFile] = useState();

Input and button

 <input type="file" id="file" onChange={(e) => setFile(e.target.files[0])} />
 <button onClick={send}>DASD</button>

Onclick function

const send = async () => {
        if (file) {
            let formData = new FormData();
            formData.append('file', file);
            console.log(formData);
            await fetch("https://localhost:44391/api/edit", 
            { method: "POST", body: formData });
        }
    }

Remove the content type from the header, as the content type is not 'text/xml it should be multipart/form-data .

Fetch api will automatically add the header based on the content. Which will be something Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD

const send = async () => {
  if (file) {
    let formData = new FormData();
    formData.append("file", file);
    console.log(formData);
    await fetch("https://localhost:44391/api/edit", {
      method: "POST",
      body: formData
    });
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM