Skip to content

Instantly share code, notes, and snippets.

@Fabianopb
Last active December 1, 2020 03:15
Show Gist options
  • Save Fabianopb/4595924936c8c92c83e3dd75bc58ec9e to your computer and use it in GitHub Desktop.
Save Fabianopb/4595924936c8c92c83e3dd75bc58ec9e to your computer and use it in GitHub Desktop.
React component for single file upload.
import React, { useState } from 'react';
import axios from 'axios';
const FileUpload = () => {
// If you are using TypeScript the state will be
// const [file, setFile] = useState<FileList | null>(null);
const [file, setFile] = useState(null);
const submitFile = async () => {
try {
if (!file) {
throw new Error('Select a file first!');
}
const formData = new FormData();
formData.append('file', file[0]);
await axios.post(`/test-upload`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
// handle success
} catch (error) {
// handle error
}
};
return (
<form onSubmit={submitFile}>
<label>Upload file</label>
<input type="file" onChange={event => setFile(event.target.files)} />
<button type="submit">Send</button>
</form>
);
};
export default FileUpload;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment