How to Loop Through formData & Make Separate POST Requests in Vue.js

preview_player
Показать описание
---

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: How to Loop Through formData & POST requests

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---

The Problem

You have a component that allows users to upload multiple images, and you want to send each image as a separate request to your backend API. The catch? Your backend does not support multiple files in one field. Unfortunately, you may find that all your API calls are sending the same last image instead of each different file.

Key Issues

Single FormData Instance: If the FormData object is created outside of your loop, the last file gets reused for all requests.

Need for Multiple Requests: Since your backend enforces one file per request, it's essential to send each file individually.

The Solution

To resolve the issue of sending the last file repeatedly, you'll need to ensure that a new FormData instance is created within your loop. Here’s how to restructure your code for clarity and functionality.

Step-by-Step Implementation

Declare formData within the Loop: Ensure that you create a new instance of FormData inside your loop that iterates through the photos array. This way, every file gets its own separate FormData object.

Here’s the adjusted method code:

[[See Video to Reveal this Text or Code Snippet]]

Handle File Uploads: Make sure that your file input properly gathers all selected files and stores them in the photos array.

File Upload Method:

[[See Video to Reveal this Text or Code Snippet]]

Why This Works

Conclusion

If you have any more questions or need further assistance, feel free to reach out! Happy coding!
Рекомендации по теме
visit shbcf.ru