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?

Om3ga
  • 24,135
  • 40
  • 122
  • 201
  • You cannot do so since browsers don's allow it. But for path when reading, [this](https://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded) might help you – Abhishek Kumar Tiwari Jun 27 '20 at 06: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. – Om3ga Jun 27 '20 at 06:51

1 Answers1

1

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

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

Kay
  • 116
  • 5