Skip to content

Instantly share code, notes, and snippets.

@gtchakama
Created September 3, 2023 08:05
Show Gist options
  • Save gtchakama/232449ac90d86477bc1d12e7d18e7c9c to your computer and use it in GitHub Desktop.
Save gtchakama/232449ac90d86477bc1d12e7d18e7c9c to your computer and use it in GitHub Desktop.
ReactJS File Upload
import React, { useState } from 'react';
import axios from 'axios';
// Define a functional component called FileUpload
const FileUpload = () => {
// Declare two state variables using the useState hook:
// - selectedFile: to store the currently selected file
// - uploadStatus: to display the upload status message
const [selectedFile, setSelectedFile] = useState(null);
const [uploadStatus, setUploadStatus] = useState('');
// Define a function handleFileChange to handle file input changes
const handleFileChange = (event) => {
// When a file is selected, update the selectedFile state with the chosen file
setSelectedFile(event.target.files[0]);
};
// Define a function handleUpload to handle the file upload process
const handleUpload = () => {
// Create a FormData object to hold the selected file
const formData = new FormData();
formData.append('file', selectedFile);
// Log the selected file (for debugging purposes)
console.log(selectedFile);
// Use Axios to send a POST request to the specified API endpoint with the file data
axios
.post('YOUR_API_ENDPOINT_HERE', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then((response) => {
// Handle a successful upload
console.log('File uploaded successfully:', response.data);
setUploadStatus('File uploaded successfully');
})
.catch((error) => {
// Handle errors that occur during the upload process
console.error('Error uploading file:', error);
setUploadStatus('Error uploading file');
});
};
// Render the file upload form and display the upload status
return (
<div>
<h2>File Upload</h2>
{/* Create an input element for selecting files and attach the handleFileChange function to its onChange event */}
<input type="file" onChange={handleFileChange} />
{/* Create a button to trigger the file upload process and attach the handleUpload function to its onClick event */}
<button onClick={handleUpload} className='border p-2 bg-green-400'>Upload</button>
{/* Display the upload status message */}
<p>{uploadStatus}</p>
</div>
);
};
// Export the FileUpload component as the default export
export default FileUpload;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment