How to Handle File Upload in React: Simple Guide
<input type='file'> element with an onChange handler to capture the selected file. Then, use FormData to send the file to a server via fetch or axios.Why This Happens
Many beginners try to upload files in React by directly reading the input value or sending the file object incorrectly, which causes errors or no file being sent.
This happens because file inputs are special and their value is read-only; you must access the file from the files property of the input event target.
import React, { useState } from 'react'; function FileUpload() { const [file, setFile] = useState(null); const handleChange = (e) => { // Incorrect: trying to get file from e.target.value setFile(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); console.log('File to upload:', file); // This will not work because file is a string, not a File object }; return ( <form onSubmit={handleSubmit}> <input type="file" onChange={handleChange} /> <button type="submit">Upload</button> </form> ); } export default FileUpload;
The Fix
To fix this, access the file from e.target.files[0] inside the onChange handler. Then use FormData to send the file in a POST request.
This ensures you get the actual file object and can upload it properly.
import React, { useState } from 'react'; function FileUpload() { const [file, setFile] = useState(null); const handleChange = (e) => { setFile(e.target.files[0]); }; const handleSubmit = async (e) => { e.preventDefault(); if (!file) return alert('Please select a file first'); const formData = new FormData(); formData.append('file', file); try { const response = await fetch('/upload', { method: 'POST', body: formData }); if (response.ok) { alert('File uploaded successfully'); } else { alert('Upload failed'); } } catch (error) { alert('Error uploading file'); } }; return ( <form onSubmit={handleSubmit}> <input type="file" onChange={handleChange} aria-label="File upload input" /> <button type="submit">Upload</button> </form> ); } export default FileUpload;
Prevention
Always access files from e.target.files instead of e.target.value. Use FormData to send files in POST requests. Add aria-label for accessibility on file inputs. Validate file selection before upload to avoid errors.
Use linting tools like ESLint with React plugins to catch common mistakes early.
Related Errors
1. Sending file as JSON: Trying to send a file by JSON.stringify causes errors because files are binary data.
2. Not using FormData: Uploads fail if you send files as plain text or URL encoded data.
3. Missing enctype on form: When using plain HTML forms, forgetting enctype="multipart/form-data" prevents file upload.