I'm sending a file from the client to a Flask API.
I've tried doing e.preventDefault()
, e.stopPropagation()
, and return false for onsubmit
on the form, but it still refreshes the page.
I need the web to hold onto some information the API will send back but it disappears after the page refreshes. I've tried using local storage to store the data but it goes away when the page refreshes. Sorry if its a stupid question :pray:
const form = document.querySelector("#upload-form");
const uploadBtn = document.querySelector("#upload-btn");
const uploadInp = document.querySelector("#upload-input");
const sendFile = async () => {
let formData = new FormData();
formData.append("file", uploadInp.files[0]);
await fetch(apiPOST, {
method: "POST",
body: formData,
})
.then((res) => res.json())
.then((json) => {
console.log(json);
})
.catch((err) => console.log(err));
};
uploadBtn.addEventListener("click", (e) => {
e.preventDefault();
sendFile();
});
<form id="upload-form" enctype="multipart/form-data" method="post" onsubmit="return false">
<label for="upload-input" class="btn">Upload File</label>
<input type="file" id="upload-input" name="upload-input" accept=".pptx"/>
<!-- <button id="upload-btn">Upload</button> -->
<input type="submit" id="upload-btn" value="Upload" />
</form>
You should call the preventDefault method from the form submit attribute, not your button.
Check this answer for more info