Use FileReader to encode the file as Base64 and then upload it through AJAX,

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.