Vinod Kumar
Vinod Kumar

Reputation: 337

How to attach file upload with state values

This is my React State

this.state = {
            data : {
                employee_Name:"" ,
                employee_Id:"",
                employee_Doj:"",
                employee_ResumeFile:""
             }
}

I am getting uploaded file data on change

onChangeHandler=event=>{
    const data = { ...this.state.data }; 
    data.employee_ResumeFile = event.target.files[0];
    this.setState({ data }); 
    console.log(data);

}

How to add this to my axios along with existing state data

doSubmit() {    
   // How to add this form data inside my axios
    const data = new FormData() 
    data.append('file', this.state.data.employee_ResumeFile)

   axios.put(apiEndpoint+'/update/'+this.props.match.params.id+'/basic-details',{
        employee_Name:this.state.data.employee_Name, 
        employee_Id: this.state.data.employee_Id,
        employee_Doj:this.state.data.employee_Doj, 
        employee_ResumeFile.state.data.employee_ResumeFile
      })
}

Should we use only formdata() to send file if then how to add formdata value inside my axios with existing values

Upvotes: 1

Views: 562

Answers (2)

gdh
gdh

Reputation: 13682

Yes use FormData and make sure to add correct headers.

Like this

doSubmit() {   
     const data = new FormData() 
     data.append('file', this.state.data.employee_ResumeFile)
     data.append('name', this.state.data.employee_Name)
     data.append('id', this.state.data.employee_Id)
     data.append('doj', this.state.data.employee_Doj)
     const config = {
        headers: {
            'content-type': 'multipart/form-data' // <-- Set header for 
        }
    }
    axios.put(apiEndpoint+'/update/'+this.props.match.params.id+'/basic-details',data, config)
 }

Editing based on comments. If lot of stuff needs to be appended to formdata, then you can maintain it in an object and loop thru it using for in and dynamically append stuff to formData.

As I see in your question that you have fields maintained in the state, so you can do something like this.

    ...
    const data = new FormData() 
    for(let key in this.state.data) {
        data.append(key,this.state.data[key]);
    }
    ...
    // axios.post code....

Upvotes: 2

Sachin Muthumala
Sachin Muthumala

Reputation: 765

Use FormData and append the file that you want to upload,

const data = new FormData() 
data.append('file', this.state.data.employee_ResumeFile)

axios.put(apiEndpoint+'/update/'+this.props.match.params.id+'/basic-details', data)

try to do REST API using post method except put.

Upvotes: 0

Related Questions