A multipart/form-data is a type of encoding used in data submissions made through HTML forms.
This type of encoding is typically used when users submit files or binary data in addition to plain text values.
The data is split into multiple parts, each separated by a boundary, and each part can contain its own set of headers that describe its content.
The multipart/form-data encoding is often used in HTTP requests made to upload files to a server.
The multipart/form-data format is specified in the HTML standard and is supported by most web browsers and servers.
In React, you can use the multipart/form-data encoding in your forms by implementing a custom submit handler and constructing a FormData object from the form values. Here is an example:
import React, { useState } from "react";
function MyForm() {
const [file, setFile] = useState(null);
const [text, setText] = useState("");
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData();
formData.append("file", file);
formData.append("text", text);
const response = await fetch("/server/upload", {
method: "POST",
body: formData
});
const result = await response.json();
console.log(result);
};
const handleFileChange = (event) => {
setFile(event.target.files[0]);
};
const handleTextChange = (event) => {
setText(event.target.value);
};
return (
<form onSubmit={handleSubmit}>
<input type="file" onChange={handleFileChange} />
<input type="text" value={text} onChange={handleTextChange} />
<button type="submit">Submit</button>
</form>
);
}
export default MyForm;
In this example, a custom submit handler is defined that constructs a FormData object from the file and text inputs.
The FormData object is then sent to the server in the body of a POST request. Note that this is a simplified example and does not include error handling or other features that you would typically include in a production-ready implementation.