Home > Mobile >  upload multiple files from a form react js throgh axios
upload multiple files from a form react js throgh axios

Time:10-06

i am trying to do multiple file upload i am only able to do one file now how can i upload 3 files from differt input fileds

import React from "react";
import axios, { post } from "axios";
;
import moment from "moment";
import "./calendar.css";

export default class Dashboard extends React.Component {
  constructor(props) {
    super(props);
  
    this.state = {
    
    
     
      image_file: null,
      image_preview: "",
      file: null,
    };
    this.onsubmbit = this.onsubmbit.bind(this);
    this.onChange = this.onChange.bind(this);
   
  }

  changeHandler = (e) => {
    this.setState({
      allValues: { ...this.state.allValues, [e.target.name]: e.target.value },
    });
  };

  onChange(e) {
   
    console.log(e.target.files[0]);


    let image_as_files = e.target.files[0];

    this.setState({
     
      image_file: image_as_files,
    });

  }
  

  onsubmbit = (e) => {
    e.preventDefault();
    if (this.state.image_file !== null) {
      let formData = new FormData();
      formData.append("scanReport", this.state.image_file);
    

      axios
        .post(
          "url/",
          formData,
          {
            headers: {
              Authorization: `token `   localStorage.getItem("token"),
              "Content-type": "multipart/form-data",
            },
          }
        )
        .then((res) => {
          console.log(`Success`   res.data);
        })
        .catch((err) => {
          console.log(err);
        });
    }
  };


 
 

  render() {
    return (
      <>
      
          <form onSubmit={this.onsubmbit}>
            <div className="module-wrap" style={styles.module}>
             
                <h4>Upload Scan Report</h4>
                <input
                  type="file"
                  id="file"
                  name="ScanReport"
                  // accept="application/pdf"
                  onChange={this.onChange}
                  value={this.state.allValues.ScanReport}
                />
                <h4>Upload Blood Report</h4>
                <input
                  type="file"
                  name="BloodReport"
                  onChange={this.onChange}
                  value={this.state.allValues.BloodReport}
                />
                <h4>Upload Antenatal Charts</h4>
                <input
                  type="file"
                  name="AntenatalCharts"
                  onChange={this.onChange}
                  value={this.state.allValues.AntenatalCharts}
                />
                <h4>Enter Today BP</h4>
                <input
                  type="text"
                  name="bp"
                  onChange={this.changeHandler}
                  value={this.state.allValues.bp}
                />
                <h4>Enter Todays Weight</h4>
                <input
                  type="text"
                  name="Weight"
                  onChange={this.changeHandler}
                  value={this.state.allValues.Weight}
                />
              </div>

              <br />

              <div>
                <button type="submit" style={styles.sbtn}>
                  Submit
                </button>
              </div>
            </div>
          </form>
      
      </>
    );
  }
}

i am trying to do multiple file upload i am only able to do one file now how can i upload 3 files from differt input fileds i am trying to do multiple file upload i am only able to do one file now how can i upload 3 files from differt input fileds

CodePudding user response:

If I understand correctly you already have it working for the one file (ScanReport), thus all you need to do is update your onChange method to be aware of the input name attribute to support multiple file inputs. And then update your class state accordingly.

Thus your state should look something like this:

this.state = {
  allValues: {
    AppointmentDate: "",
    Date: "",
    ScanDate: "",
    question: "",
    ScanReport: "",
    BloodReport: "",
    AntenatalCharts: "",
    Weight: "",
  },
  files: {
    ScanReport: null, // <- these keys should match the 'name' of the inputs
    BloodReport: null,
    AntenatalCharts: null
  },
  image_preview: "",
  file: null,
}

Then update your onChange to use the name attribute to set it accordingly:

onChange(e) {
  let files = this.state.files
  files[e.target.name] = e.target.files[0]

  this.setState({  
    files: files
  });
}

And then finally when you construct the FormData you can add each individual file with the required field name in the form data:

let formData = new FormData();

// EDIT: added logic to handle null files
if (this.state.files.ScanReport != null) {
  formData.append("scanReport", this.state.files.ScanReport);
}
if (this.state.files.BloodReport != null) {
  formData.append("bloodReport", this.state.files.BloodReport);
}
if (this.state.files.AntenatalCharts != null) {
  formData.append("antenatalCharts", this.state.files.AntenatalCharts);
}

...

  • Related