1

I have below code:

class DashboardPage extends Component {
  
  handleNewProduct = event => {
    event.preventDefault();

    console.log(event.target.files);

    let formData = new FormData();

    formData.append('title', event.target.title.value);
    formData.append('desc', event.target.desc.value);
    formData.append('image', event.target.product.value);

    // console.log(formData);
    formData.forEach((item) => {
        console.log(item)
    });
  }

  render() {
    return (
      <>
        <h2>Enter New product.</h2>
        <form onSubmit={this.handleNewProduct} encType="multipart/form-data">
            <div>
                <label>Title</label>
                <input type="text" name="title" />
            </div>
            <div>
                <label>Desciption</label>
                <textarea type="text" name="desc"></textarea>
            </div>
            <div>
                <input type="file" name="product" />
            </div>
            <div>
                <button>Submit</button>
            </div>
        </form>
      </>
    );
  }
}

It gets all the information from form and logs in it out. I append the data to formData which is an instance of FormData. But for file I gets the path of the file. How to get the file to store to formData and then upload it to server using lets say fetch api?

2
  • You cannot do so since browsers don's allow it. But for path when reading, this might help you Commented Jun 27, 2020 at 6:49
  • @AbhishekKumarTiwari I am not planning to preview it. I just want to select a image and enter some information like title and description and then post it. Commented Jun 27, 2020 at 6:51

1 Answer 1

1

Referring https://stackoverflow.com/a/22404816/9554128

You might want to do event.target.product.files[0]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.