SoFunction
Updated on 2025-04-13

How to handle the front-end with formdata for transfer parameters?

Preface

When the backend requires itFormDataWhen passing parameters, the front-end needs to format the data asFormDataObject, and passPOSTRequest to send. The following is the processingFormDataDetailed steps and sample code for passing parameters:

1. What is FormData?

FormDataIt 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 emptyFormDataObject.

Step 2: Add data to FormData

useappendMethods to add data toFormDataIn the object.

Step 3: Send a request

WillFormDataThe 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 receiveusernameandpasswordTwo 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 receiveusernameandavatar(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

    • useFormDataWhen the browser will automatically setContent-Typeformultipart/form-data, so manual settings are not required.
    • If set manuallyContent-Type, which may cause the request to fail.
  • File size limit

    • If you need to upload large files, make sure that the backend supports sharded upload or streaming upload.
  • compatibility

    • FormDataIt 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 useXMLHttpRequestreplacefetch

5. Use Axios to send FormData

If you useaxiosSend 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 checkFormDataThe following methods can be used for the content of  :

for (let [key, value] of ()) {
  (key, value);
}

7. Backend Receive FormData

Backend ReceiveFormDataThe way   depends on the framework used:

  • + Express:usemulterorformidablemiddleware.
  • Python Flask:useand
  • Spring Boot:use@RequestParamorMultipartFile

Through the above methods, you can easily handle front-end use.FormDataRequirements 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!