Home >Backend Development >PHP Tutorial >Refresh-free file upload tutorial using PHP and HTML5 FormData
This article mainly introduces the tutorial of using PHP and HTML5 FormData to implement refresh-free file upload. This article first breaks down the steps of writing the program, and finally gives a complete example. Friends in need can refer to it
No-refresh file upload is a A common but somewhat complicated problem, a common solution is to construct an iframe.
In HTML5, a FormData object API is provided. Through FormData, a form request can be easily constructed and sent through XMLHttpRequest. It is also possible to send files through the FormData object, so uploading without refreshing becomes very simple.
So how to use FormData? Script House will give a brief introduction to this below.
1. Construct a FormData object
If you want to get a FormData object, it is very simple:
The FormData object only provides one method append, which is used to add form request parameters to the object.
In current mainstream browsers, FormData can be obtained or modified in the following two ways.
Method 1: Create an empty FormData object, and then use the append method to add key-value pairs one by one. Example:
This method does not require the existence of HTML form objects.
Method 2: Obtain the form element object and pass it into the FormData object as a parameter. Example:
Of course, you can also use the append method to continue adding other parameters to fd.
2. FormData sends a request
Now that I have obtained the FormData object, how do I send a request? The FormData object is mainly used in the send method of the enhanced XMLHttpRequest object. Refer to the following example:
3. Using FormData in jquery
In the ajax method of jQuery, you can also use the FormData method to achieve refresh-free upload. But please pay attention to the parameter settings, the reference is as follows:
4. A complete example (including PHP processing example):