Preface
When the backend requires itFormData
When passing parameters, the front-end needs to format the data asFormData
Object, and passPOST
Request to send. The following is the processingFormData
Detailed steps and sample code for passing parameters:
1. What is FormData?
FormData
It is an object used to construct form data, usually used to upload files or send key-value pairs of data. It supports text, files, blobs and other data types.
2. How to deal with FormData parameter transmission in the front-end?
Step 1: Create a FormData object
usenew FormData()
Create an emptyFormData
Object.
Step 2: Add data to FormData
useappend
Methods to add data toFormData
In the object.
Step 3: Send a request
WillFormData
The object is sent to the backend as a request body.
3. Sample code
Example 1: Send normal key-value pair data
Assume that the backend needs to receiveusername
andpassword
Two fields:
// Create a FormData objectconst formData = new FormData(); // Add data('username', 'admin'); ('password', '123456'); // Send a requestfetch('/api/login', { method: 'POST', body: formData, // Use FormData as the request body}) .then(response => ()) .then(data => (data)) .catch(error => ('Error:', error));
Example 2: Send a file
Suppose the backend needs to receive a file (such as user avatar):
<input type="file" /> <button onclick="uploadFile()">Upload file</button> <script> function uploadFile() { const fileInput = ('avatar'); const file = [0]; // Get the file selected by the user if (!file) { alert('Please select a file'); return; } // Create a FormData object const formData = new FormData(); ('file', file); // Add files to FormData // Send a request fetch('/api/upload', { method: 'POST', body: formData, // Use FormData as the request body }) .then(response => ()) .then(data => (data)) .catch(error => ('Error:', error)); } </script>
Example 3: Send mixed data (text + file)
Assume that the backend needs to receiveusername
andavatar
(User avatar file):
<input type="text" placeholder="username" /> <input type="file" /> <button onclick="submitForm()">submit</button> <script> function submitForm() { const username = ('username').value; const fileInput = ('avatar'); const file = [0]; // Get the file selected by the user if (!username || !file) { alert('Please fill in the username and select the file'); return; } // Create a FormData object const formData = new FormData(); ('username', username); // Add text data ('avatar', file); // Add file data // Send a request fetch('/api/submit', { method: 'POST', body: formData, // Use FormData as the request body }) .then(response => ()) .then(data => (data)) .catch(error => ('Error:', error)); } </script>
4. Things to note
-
Request header:
- use
FormData
When the browser will automatically setContent-Type
formultipart/form-data
, so manual settings are not required. - If set manually
Content-Type
, which may cause the request to fail.
- use
-
File size limit:
- If you need to upload large files, make sure that the backend supports sharded upload or streaming upload.
-
compatibility:
-
FormData
It is well supported in modern browsers, but may not be supported in some older browsers (such as IE 10 below). If you need to be compatible with older browsers, you can useXMLHttpRequest
replacefetch
。
-
5. Use Axios to send FormData
If you useaxios
Send a request, you can handle it like this:
const formData = new FormData(); ('username', 'admin'); ('avatar', file); // Assume that file is a user-selected file ('/api/submit', formData, { headers: { 'Content-Type': 'multipart/form-data', // axios will be processed automatically, and you can omit this }, }) .then(response => ()) .catch(error => ('Error:', error));
6. Debugging FormData
If you want to checkFormData
The following methods can be used for the content of :
for (let [key, value] of ()) { (key, value); }
7. Backend Receive FormData
Backend ReceiveFormData
The way depends on the framework used:
-
+ Express:use
multer
orformidable
middleware. -
Python Flask:use
and
。
-
Spring Boot:use
@RequestParam
orMultipartFile
。
Through the above methods, you can easily handle front-end use.FormData
Requirements for transferring ginseng. If there are more complex requirements (such as multi-file upload, shard upload, etc.), the implementation can be further expanded. .
This is the article about how to handle the front-end of formdata transmission and parameter transfer in the back-end. For more related front-end processing of formdata transmission and parameter transfer in the back-end, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!