Use FileReader to encode the file as Base64 and then upload it through AJAX,
You cannot directly upload files using AJAX. Generally, a new iframe is used to complete the form submission process in order to achieve asynchronous file upload.
This can achieve better browser compatibility, but the amount of code will be relatively large, even if the file upload plug-in is used, such as plupload.
How can we achieve flexibility? Just treat a file as a common form parameter like submitting form data through AJAX.
With a flash of light, it's okay to use the javascript FileReader object to encode the file into base64 and then transfer it to the server ~
Start to work.
The front end uses base64 to encode the file and transmits it to the server through ajax:
The backend decodes and saves the file data:
<?phpif (isset($_POST['file_base64'])){ $file_base64 = $_POST['file_base64']; $file_base64 = preg_replace('/data:.*;base64,/i', '', $file_base64); $file_base64 = base64_decode($file_base64); file_put_contents('./file.save', $file_base64);}
Mainstream browsers support FileReader objects in javascript and IE10 or above. I personally think that this asynchronous file upload method can be considered when providing services for a small range of areas, saving time and effort, and compatibility with the IE series is another matter.
Articles you may be interested in:
- Asynchronous Multifile upload using native JavaScript
- Js Implementation of input type = "file" file Upload sample code
- Jsp page implementation file upload and download class code