158

I actually have a file input and I would like to retrieve the Base64 data of the file.

I tried:

$('input#myInput')[0].files[0] 

to retrieve the data. But it only provides the name, the length, the content type but not the data itself.

I actually need these data to send them to Amazon S3

I already test the API and when I send the data through html form with encode type "multipart/form-data" it works.

I use this plugin : http://jasny.github.com/bootstrap/javascript.html#fileupload

And this plugins gives me a preview of the picture and I retrieve data in the src attribute of the image preview. But when I send these data to S3 it does not work. I maybe need to encode the data like "multipart/form-data" but I don't know why.

Is there a way to retrieve these data without using an html form?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
kschaeffler
  • 3,663
  • 7
  • 29
  • 41
  • In order to have contents you're going to need to upload it in some fashion (iframe, ajax, flash, or traditional form). – Brad Christie Sep 05 '12 at 12:48
  • The file must be uploaded to the server first. – Sven van Zoelen Sep 05 '12 at 12:48
  • 5
    Not necessarily, if the browser supports the new File API (see http://www.html5rocks.com/en/tutorials/file/dndfiles/) – devnull69 Sep 05 '12 at 12:50
  • I'm actually using this plugin http://jasny.github.com/bootstrap/javascript.html#fileupload and I can get a preview of the file so the data are somewhere. – kschaeffler Sep 05 '12 at 12:52
  • in that case the "data" will be on the server. You'll have to output the data to the client (browser) before you can access it via Javascript/jQuery – devnull69 Sep 05 '12 at 13:05
  • I think that the plugin that I use already do that. I can retrieve some data in the image preview file but that's just a part of the data not all the file data. – kschaeffler Sep 05 '12 at 13:07

8 Answers8

181

input file element:

<input type="file" id="fileinput" />

get file :

var myFile = $('#fileinput').prop('files');
Morilog
  • 2,315
  • 2
  • 13
  • 15
141

You can try the FileReader API. Do something like this:

<!DOCTYPE html>
<html>
  <head>
    <script>        
      function handleFileSelect()
      {               
        if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
          alert('The File APIs are not fully supported in this browser.');
          return;
        }   
      
        var input = document.getElementById('fileinput');
        if (!input) {
          alert("Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
          alert("This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
          alert("Please select a file before clicking 'Load'");               
        }
        else {
          var file = input.files[0];
          var fr = new FileReader();
          fr.onload = receivedText;
          //fr.readAsText(file);
          //fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
          fr.readAsDataURL(file);
        }
      }
      
      function receivedText() {
        document.getElementById('editor').appendChild(document.createTextNode(fr.result));
      }           
      
    </script>
  </head>
  <body>
    <input type="file" id="fileinput"/>
    <input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
    <div id="editor"></div>
  </body>
</html>
GalaxyCat105
  • 2,105
  • 4
  • 12
  • 26
Sark
  • 4,022
  • 4
  • 23
  • 24
  • Hey, I tried your solution and that works. I retrieved the information but it's not well encoded. For a file I get `\xc3\xbf\xc3` instead of getting this encode `\xff\xd8\xff` for the 3 first characters of my picture. What should I use to get the second encode for my picture? – kschaeffler Sep 06 '12 at 10:22
  • @kschaeffler try fr.readAsDataURL(file); this is function reading Base64 datas, but i haven't tested it yet. – Sark Sep 06 '12 at 11:22
  • actually this function give me not enough data. that's already what I have from the preview that I use in the plugin jasny.github.com/bootstrap/javascript.html#fileupload. I think that the data I retrieve are not Base64 encoded and this is the problem, but I'm not sure – kschaeffler Sep 06 '12 at 13:48
  • I actually need the same encode data that I retrieve when I post through html form with the "multipart/form-data" encode type – kschaeffler Sep 06 '12 at 15:41
54

I created a form data object and appended the file:

var form = new FormData(); 
form.append("video", $("#fileInput")[0].files[0]);

and i got:

------WebKitFormBoundaryNczYRonipfsmaBOK
Content-Disposition: form-data; name="video"; filename="Wildlife.wmv"
Content-Type: video/x-ms-wmv

in the headers sent. I can confirm this works because my file was sent and stored in a folder on my server. If you don't know how to use the FormData object there is some documentation online, but not much. Form Data Object Explination by Mozilla

mark.inman
  • 2,152
  • 2
  • 16
  • 12
46

Html:

<input type="file" name="input-file" id="input-file">

jQuery:

var fileToUpload = $('#input-file').prop('files')[0];

We want to get first element only, because prop('files') returns array.

cerbin
  • 1,100
  • 10
  • 26
20

input element, of type file

<input id="fileInput" type="file" />

On your input change use the FileReader object and read your input file property:

$('#fileInput').on('change', function () {
    var fileReader = new FileReader();
    fileReader.onload = function () {
      var data = fileReader.result;  // data <-- in this var you have the file data in Base64 format
    };
    fileReader.readAsDataURL($('#fileInput').prop('files')[0]);
});

FileReader will load your file and in fileReader.result you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)

Carlos B. Flores
  • 1,485
  • 12
  • 9
12

FileReader API with jQuery, simple example.

( function ( $ ) {
 // Add click event handler to button
 $( '#load-file' ).click( function () {
  if ( ! window.FileReader ) {
   return alert( 'FileReader API is not supported by your browser.' );
  }
  var $i = $( '#file' ), // Put file input ID here
   input = $i[0]; // Getting the element from jQuery
  if ( input.files && input.files[0] ) {
   file = input.files[0]; // The file
   fr = new FileReader(); // FileReader instance
   fr.onload = function () {
    // Do stuff on onload, use fr.result for contents of file
    $( '#file-content' ).append( $( '<div/>' ).html( fr.result ) )
   };
   //fr.readAsText( file );
   fr.readAsDataURL( file );
  } else {
   // Handle errors here
   alert( "File not selected or browser incompatible." )
  }
 } );
} )( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" />
<input type='button' id='load-file' value='Load'>
<div id="file-content"></div>

To read as text... uncomment //fr.readAsText(file); line and comment fr.readAsDataURL(file);

shramee
  • 3,632
  • 19
  • 37
0
 <script src="~/fileupload/fileinput.min.js"></script>
 <link href="~/fileupload/fileinput.min.css" rel="stylesheet" />

Download above files named fileinput add the path i your index page.

<div class="col-sm-9 col-lg-5" style="margin: 0 0 0 8px;">
<input id="uploadFile1" name="file" type="file" class="file-loading"       
 `enter code here`accept=".pdf" multiple>
</div>

<script>
        $("#uploadFile1").fileinput({
            autoReplace: true,
            maxFileCount: 5
        });
</script>
Amit Rana
  • 57
  • 7
0

HTML

<div class="row form-group my-2">
                <div class="col-12">
                    <div class="">
                        <div class="text-center">
                            <label for="inpImage" class="m-2 pointer">
                                <img src="src/img/no-image.jpg" id="img-visor" height="120" class="rounded mx-auto d-block">
                            </label>
                            <input type="file" class="visually-hidden" accept="image/*" name="picture" id="inpImage">
                        </div>
                    </div>
                </div>
            </div>

jQuery

$('#inpImage').change(()=>{
const file = $('#inpImage').prop("files")[0];
const imagen = URL.createObjectURL(file);
console.log(URL.createObjectURL(file));
$('#img-visor').attr('src', imagen);
});