Home > Article > Web Front-end > File encoded base64 for upload via AJAX
This time I will introduce to you what are the precautions for file encoding base64 uploading through AJAX. The following is a practical case, let's take a look.
z It is impossible to upload files directly using AJAX. Generally, a new iframe is created in which the form submission process is completed to achieve the effect of asynchronously uploading files.
This can achieve better browser compatibility, but the amount of code will be relatively large, even if a file upload plug-in is used, such as plupload.
How can we achieve a level of flexibility? It would be great if we could treat files as ordinary form parameters just like ordinary AJAX submission of form data.
I suddenly had an idea, wouldn’t it be enough to use the FileReader object of javascript to encode the file into base64 and then transmit it to the server~
Start doing it and have enough food and clothing.
The front-end base64 encodes the file and transmits it to the server through ajax:
<head> <meta charset="UTF-8"> </head> <form onsubmit="return false;"> <input type="hidden" name="file_base64" id="file_base64"> <input type="file" id="fileup"> <input type="submit" value="submit" onclick="$.post('./uploader.php', $(this).parent().serialize());"> </form> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script> $(document).ready(function(){ $("#fileup").change(function(){ var v = $(this).val(); var reader = new FileReader(); reader.readAsDataURL(this.files[0]); reader.onload = function(e){ console.log(e.target.result); $('#file_base64').val(e.target.result); }; }); }); </script>
The back-end decodes and saves the file data:
<?php if (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); }
FileReader object in javascript mainstream browsers They are all supported, and IE10 and above support it. I think this asynchronous file upload method can be considered when providing services to a small range, which saves time and effort. Compatibility with the IE series is another matter.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
angular print page specified function
##Use Element-UI Table to implement drag and drop function
The above is the detailed content of File encoded base64 for upload via AJAX. For more information, please follow other related articles on the PHP Chinese website!