Basically you have to create a form with the fields with their names and types and use it in a simple way fetch to send data with Formdata in your body (body
) as in the example below:
React Rook
import React, { useRef } from "react";
export default function Form() {
const formRef = useRef();
function onSubmitForm(e) {
e.preventDefault();
const data = new FormData(formRef.current);
const settings = {
method: "POST",
mode: "cors",
cache: "default",
body: data
};
const url = ""; // endereço do serviço
fetch(url, settings)
.then(response => response.json())
.then(response => console.log(response))
.catch(error => console.error(error));
}
return (
<>
<form name='form1' ref={formRef} id='form1' onSubmit={onSubmitForm}>
<div>
<label htmlFor='file'>File</label>
<input type='file' name='File' id='File' />
</div>
<div>
<label htmlFor='Param'>Param</label>
<input type='text' name='Param' id='Param' />
</div>
<button>Send</button>
</form>
</>
);
}
React Class
import React, { Component } from "react";
export default class Forms extends Component {
constructor() {
super();
this.onSubmitForm = this.onSubmitForm.bind(this);
this.formRef = React.createRef();
}
onSubmitForm = e => {
e.preventDefault();
const data = new FormData(this.formRef.current);
const settings = {
method: "POST",
mode: "cors",
cache: "default",
body: data
};
const url = ""; // endereço do serviço
fetch(url, settings)
.then(response => response.json())
.then(response => console.log(response))
.catch(error => console.error(error));
};
render() {
return (
<form name="form1" ref={this.formRef} id="form1" onSubmit={this.onSubmitForm}>
<div>
<label htmlFor="file">File</label>
<input type="file" name="File" id="File" />
</div>
<div>
<label htmlFor="Param">Param</label>
<input type="text" name="Param" id="Param" />
</div>
<button>Send</button>
</form>
);
}
}
With these codes is the class FileInputModel
will be filled with the information and image sent.
Are you wanting to send from a form or Ajax, as you are sending? (I imagine it is Ajax but I was in doubt...)
– novic
I am using React sending via REST api, in case yes it is AJAX
– Diogo Soares