{"pageProps":{"post":{"title":"How to upload files in React using Axios","excerpt":"Learn to upload files in React using Axios post method","date":"2021-10-09T00:00:00.000Z","slug":"react-upload-file-using-axios","author":{"name":"Suraj Sharma","picture":""},"content":"\n
\n\nIn this tutorial, I will discuss how you can upload documents, images or videos in React using Axios\n\n
\n\nConsider you have a `
` component that contains an input element of `type=\"file\"` and an upload file button, which uploads the selected file to the server using the Axios `post` method.\n\n
\n\n```jsx\nimport React from 'react';\nimport axios from 'axios';\n\nconst Form = () => {\n // a local state to store the currently selected file.\n const [selectedFile, setSelectedFile] = React.useState(null);\n\n const handleSubmit = async(event) => {\n event.preventDefault()\n const formData = new FormData();\n formData.append(\"selectedFile\", selectedFile);\n try {\n const response = await axios({\n method: \"post\",\n url: \"/api/upload/file\",\n data: formData,\n headers: { \"Content-Type\": \"multipart/form-data\" },\n });\n } catch(error) {\n console.log(error)\n }\n }\n\n const handleFileSelect = (event) => {\n setSelectedFile(event.target.files[0])\n }\n\n return (\n \n \n \n
\n )\n};\n\nexport default Form;\n```\n\n
\n
\n\nLet's break the above solution into multiple steps\n\n1. First, you create a local React state `selectedFile` using `useState()` hook to store the currently selected file,\n\n2. Second, the `handleFileSelect` event handler updates the `selectedFile` value using the setter function `setSelectedFile` and,\n\n3. Third, the `handleSubmit` function handles the post request to upload file using Axios.\n\n
\n
\n\n**Related Solutions**\n\n- [How to get the size of a file in React](/blog/react-get-file-size)\n\n- [How to accept only image files in react file upload](/blog/react-file-upload-accept-only-images)\n\n- [How to submit form data in post request using axios](/blog/axios-post-form-data)\n\n- [How to handle an error in async await in JavaScript](/blog/error-handling-in-javascript-async-await)\n\n- [How to loop through an array of objects in React](/blog/for-loop-in-react)\n\n
","coverImage":{"url":"/images/cover-image.png"},"url":"react-upload-file-using-axios","hashtags":"#react #axios"}},"__N_SSG":true}