When I submit my form it gets reloaded, but when no file is selected, it doesn't get reload, just show me an error message 'No File Uploaded'. It only gets reloaded when I submit the file.
I already used the e.preventDefault() to prevent reloading but it doesn't work.
Component Code
import React, { Fragment, useState } from 'react'
import axios from 'axios'
const FileUpload = () => {
const [file, setFile] = useState('');
const [filename, setFilename] = useState('Choose File')
const [uploadedFile, setUploadedFile] = useState({})
const onChange = (e) => {
setFile(e.target.files[0]);
setFilename(e.target.files[0].name);
}
const onSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('file', file);
try {
const res = await axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
const { fileName, filePath } = res.data;
setUploadedFile({ fileName, filePath });
console.log(uploadedFile);
} catch (err) {
if (err.response.status === 500) {
console.log("There was a problem with the server.");
} else {
console.log(err.response.data.msg);
}
}
}
return (
<Fragment>
<form onSubmit={onSubmit}>
<div className="mb-3">
<label htmlFor="formFile" className="form-label">{filename}</label>
<input className="form-control" type="file" id="formFile" onChange={onChange} />
</div>
{/* <button type="submit" value="Upload" className="btn btn-primary w-100" /> */}
<button className="btn btn-primary w-100" type="submit">Upload</button>
</form>
</Fragment>
)
}
export default FileUpload
Anyone can please help me with this.
actionattribute, i.e.action="/link_to_some_page". This makes the form return to its default behavior, which is sending the data to its current URL, which is why you are experiencing this behavior. You either need to specify where the form data should be sent, or prevent the default behavior by applying thee.preventDefault()propagation to the form's submit. Alternatively, you can utilize AJAX and send the data asynchronously.e.preventDefault()to the submit event and I post data to my API URL using axios