To upload a file in React Js, we can use FormData()
api of javascript. We need to create a form with input file field and append the form value into formdata variable. Then we can send it into a POST
request. Let’s see this in action.
Code Example
import React from "react"; import axios from "axios"; export default function App() { const [uploadFile, setUploadFile] = React.useState(); const [superHero, setSuperHero] = React.useState(); const submitForm = (event) => { event.preventDefault(); const dataArray = new FormData(); dataArray.append("superHeroName", superHero); dataArray.append("uploadFile", uploadFile); axios .post("api_url_here", dataArray, { headers: { "Content-Type": "multipart/form-data" } }) .then((response) => { // successfully uploaded response }) .catch((error) => { // error response }); }; return ( <div> <form onSubmit={submitForm}> <input type="text" onChange={(e) => setSuperHero(e.target.value)} placeholder={"Superhero Name"} /> <br /> <input type="file" onChange={(e) => setUploadFile(e.target.files)} /> <br /> <input type="submit" /> </form> </div> ); }
There are few points about this code –
- For network requests I am using Axios library. You can use default fetch functions in its place.
- We are sending
POST
parameter as well asFILE
in the same request. - The
content-type
header is set tomultipart/form-data
so that file upload can work. - Replace
api_url_here
with the url on which you want to upload file, likehttps://www.example.com/uploadFile.php
We have created a form which has 2 fields – text and file. The values of these input fields are stored in state variables – superHero
and uploadFile
.
Note: For files we are using
e.target.files
and for text field,e.target.value
In our <form>
tag, we are calling submitForm()
function. Don’t forget to use event.preventDefault()
otherwise form will submit in its default html behavior and reload the application.
Next, we created a FormData()
variable and append the text field value and file value in it. With the help of Axios, we sent the data to the API.
If you are using php as backend then you can access the data using –
$_POST['superHeroName']
for text field value.
$_FILES['uploadFile']
for file field value.
You may learn more about formdata here. It’s best to use react-native-forms library to create forms in react js.