Home  >  Article  >  Web Front-end  >  Use FileReader to encode files into Base64 and then upload them through AJAX_javascript skills

Use FileReader to encode files into Base64 and then upload them through AJAX_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:23:501480browse

It is not possible to upload files directly using AJAX. Generally, you need to create a new iframe and complete the form submission process in it 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 form data.

I had an idea, wouldn’t it be enough to use JavaScript’s FileReader object to encode the file into base64 and then transmit it to the server~

Start taking action and have enough food and clothing.

The front end base64 encodes the file and transmits it to the server via 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://ajax.googleapis.com/ajax/libs/jquery/1.9.1/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 backend decodes and saves the file data:

<&#63;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);
}

The FileReader object in JavaScript is supported by all mainstream browsers, and is supported by IE10 and above. I personally think that this method of asynchronous file uploading can be considered when providing services to a small range, which saves time and effort. Compatibility with the IE series is another matter.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn