Created
March 22, 2024 20:48
-
-
Save dcortesnet/d94e84709bfc828f29f7cbaece0e8fca to your computer and use it in GitHub Desktop.
Reactjs send file to form data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react'; | |
export function App() { | |
const [file, setFile] = useState(null); | |
const handleFileChange = (event) => { | |
setFile(event.target.files[0]); | |
}; | |
const handleSubmit = (event) => { | |
event.preventDefault(); | |
const formData = new FormData(); | |
formData.append('file', file); | |
// Send the form data to the server using fetch or axios | |
fetch('/upload', { | |
method: 'POST', | |
body: formData | |
}) | |
.then(response => response.json()) | |
.then(data => { | |
// Handle the response from the server | |
console.log(data); | |
}) | |
.catch(error => { | |
// Handle any errors | |
console.error(error); | |
}); | |
}; | |
return ( | |
<div> | |
<h1>Upload File</h1> | |
<form onSubmit={handleSubmit}> | |
<input type="file" onChange={handleFileChange} /> | |
<button type="submit">Upload</button> | |
</form> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment