Reputation: 32823
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?
Upvotes: 1
Views: 399
Reputation: 126
Referring https://stackoverflow.com/a/22404816/9554128
You might want to do event.target.product.files[0]
Upvotes: 1