In our common Web front-end projects, we often encounter the need to submit forms. Normally, we submit all forms in one interface, but when there are file uploads, such as the most common image uploads, we have two ways to submit forms: One is to upload the image separately, and then submit the link address of the uploaded image as one of the form items along with other form elements. In this case, the submitted image is actually just a URL, which is also stored in the backend database. Another way to submit an image is to submit it along with the rest of the form data without pre-uploading, that is, uploading the image at the same time the form is submitted.
Most of the forms I submitted before were in the first case, uploading the image first and submitting the IMAGE URL. When I was doing a new project this time, the backend developer did not provide a single interface for uploading pictures, but only a unified form submission interface, so I adopted the second method mentioned above.
The interface Type of form submission backend provided by students is POST, and we all know that the default Content-Type of Post is Application/X-www-form-urlencoded, which is a Type submitted in key-value format. However, if we want to submit pictures (that is, upload pictures), we definitely can’t use this way, we use formData format. The key point here is that all form elements are formatted using formData.
FormData: formData (); formData: formData (); formData ();
let formData = new FormData()
Copy the code
We then need to use the append method to add form elements to the instance in turn, like this:
formData.append('title', title)
formData.append('titleContext', titleContext)
formData.append('context', context)
formData.append('tag', tag)
formData.append('time', time)
formData.append('images', file)
Copy the code
Note one detail here, that is the file of the picture. When we upload the picture using a third-party component, we will get the stream information of the picture, like this:
The content is actually the data after the image is transformed into Base64, which is generally used for preview display, while the following file is really useful for uploading data.
Before we’re done, we need to change the content-Type of the request to multipart/form-data. Of course, there may be other configurations, depending on the project.
At this point, a unified form submission method is completed, so that submission is also more convenient, do not need to request more interface, did not find before, now do know, very fragrant, do not know what pit, if you know the students still hope not hesitate to give advice, thank you!