ROHIT RAJ
ROHIT RAJ

Reputation: 196

How to Upload Image in React js and Django?

I am trying to upload an image using react js on django backend but wheni try to upload pic and check it console.log() image FILE exist there and once i submit the form image file object shsows {} empty i don't why all the time when i submitted for its shows uploaded but all the time image shows null, Here is my code so far what i did. here is also a link of code sandbox link . https://codesandbox.io/s/thirsty-varahamihira-fnusu?file=/src/App.js:0-1494. Thanks.

import React, { Component } from "react";
import "./styles.css";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      image: null
    };
  }

  handleInputChange = async (event) => {
    await this.setState({
      [event.target.name]: event.target.files[0]
      // image: event.target.files[0]
    });
  };

  handleSubmit = (e) => {
    e.preventDefault();
    const formdata = new FormData();
    formdata("image", this.state.image);
    fetch(`https://inback.herokuapp.com/api/1/blog/image/list/`, {
      method: "POST",
      headers: {
        "Content-Type": "multipart/form-data",
        Authorization: "Bearer 6tEg0RinS5rxyZ8TX84Vc6qXuR2Xxw"
      },
      body: formdata
    })
      .then((response) => {
        if (response.ok) {
          alert("Success");
        } else {
          alert("error");
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  render() {
    return (
      <div id="other" className="">
        <p className="mod" style={{ marginTop: "10px" }}>
          Uplaod
        </p>
        <hr></hr>

        <form onSubmit={this.handleSubmit}>
          <input type="file" name="image" onChange={this.handleInputChange} />
          <button>Submit</button>
        </form>
      </div>
    );
  }
}

export default App;

Upvotes: 1

Views: 9037

Answers (2)

Cuong DaoVan
Cuong DaoVan

Reputation: 342

please try using formdata like this:

formdata.append("image", this.state.image);

Upvotes: 2

ROHIT RAJ
ROHIT RAJ

Reputation: 196

Thanks , I am able to solve this issue, here is working code and sandbox link. https://codesandbox.io/s/naughty-maxwell-ojnql?file=/src/App.js:0-1344.

import React, { Component } from "react";
import axios from "axios";
import "./styles.css";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      image: null
    };
  }

  handleInputChange = async (event) => {
    event.preventDefault();
    await this.setState({
      // [event.target.name]: event.target.files[0]
      image: event.target.files[0]
      // image: event.target.files[0]
    });
  };

  handleFormSubmit = (event) => {
    event.preventDefault();

    let data = new FormData(); // creates a new FormData object

    data.append("image", this.state.image); // add your file to form data

    axios({
      method: "POST",
      url: "https://inback.herokuapp.com/api/1/blog/image/list/",
      headers: {
      
        Authorization: "Bearer 6tEg0RinS5rxyZ8TX84Vc6qXuR2Xxw"
      },
      data
    })
      .then((res) => console.log(res))
      .catch((err) => console.log(err));
  };

  render() {
    return (
      <div id="other" className="">
        <p className="mod" style={{ marginTop: "10px" }}>
          Uplaod
        </p>
        <hr></hr>

        <form onSubmit={this.handleFormSubmit}>
          <input type="file" name="image" onChange={this.handleInputChange} />
          <button>Submit</button>
        </form>
      </div>
    );
  }
}

export default App;

Upvotes: 2

Related Questions