Skip to content

Instantly share code, notes, and snippets.

@dcortesnet
Created March 22, 2024 20:48
Show Gist options
  • Save dcortesnet/d94e84709bfc828f29f7cbaece0e8fca to your computer and use it in GitHub Desktop.
Save dcortesnet/d94e84709bfc828f29f7cbaece0e8fca to your computer and use it in GitHub Desktop.
Reactjs send file to form data
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