Get Base64 encode file-data from Input Form

Viewed 320580

I've got a basic HTML form from which I can grab a bit of information that I'm examining in Firebug.

My only issues is that I'm trying to base64 encode the file data before it's sent to the server where it's required to be in that form to be saved to the database.

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

And in Javascript+jQuery:

var file = $('#fileupload').attr("files")[0];

I have some operations based on available javascript: .getAsBinary(), .getAsText(), .getAsTextURL

However none of these return usable text that can be inserted as they contain unusable 'characters' - I don't want to have a 'postback' occur in my file uploaded, and I need to have multiple forms targeting specific objects so it's important I get the file and use Javascript this way.

How should I get the file in such a way that I can use one of the Javascript base64 encoders that are widely available!?

Thanks

Update - Starting bounty here, need cross-browser support!!!

Here is where I'm at:

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

<script type="text/javascript">
var uploadformid = 'fileuploadform';
var uploadform = document.getElementById(uploadformid);


/* method to fetch and encode specific file here based on different browsers */

</script>

Couple of issues with cross browser support:

var file = $j(fileUpload.toString()).attr('files')[0];
fileBody = file.getAsDataURL(); // only would works in Firefox

Also, IE doesn't support:

var file = $j(fileUpload.toString()).attr('files')[0];

So I have to replace with:

var element = 'id';
var element = document.getElementById(id);

For IE Support.

This works in Firefox, Chrome and, Safari (but doesn't properly encode the file, or at least after it's been posted the file doesn't come out right)

var file = $j(fileUpload.toString()).attr('files')[0];
var encoded = Btoa(file);

Also,

file.readAsArrayBuffer() 

Seems to be only supported in HTML5?

Lots of people suggested: http://www.webtoolkit.info/javascript-base64.html

But this only returns an error on the UTF_8 method before it base64 encodes? (or an empty string)

var encoded = Base64.encode(file); 
8 Answers

Inspired by @Josef's answer:

const fileToBase64 = async (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (e) => reject(e)
  })

const file = event.srcElement.files[0];
const imageStr = await fileToBase64(file)

Complete example

Html file input

<style>
.upload-button {
  background-color: grey;
}

.upload-button input{
  display:none;
}
</style>
<label for="upload-photo" class="upload-button">
    Upload file
    <input
     type="file"
     id="upload-photo"
    </input>
</label>

JS Handler

document.getElementById("upload-photo").addEventListener("change", function({target}){
 if (target.files && target.files.length) {
      try {
        const uploadedImageBase64 = await convertFileToBase64(target.files[0]); 
        //do something with above data string 
      } catch() {
        //handle error
      }
    }
})

function convertFileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    // Typescript users: use following line
    // reader.onload = () => resolve(reader.result as string);
    reader.onerror = reject;
  });
}

After struggling with this myself, I've come to implement FileReader for browsers that support it (Chrome, Firefox and the as-yet unreleased Safari 6), and a PHP script that echos back POSTed file data as Base64-encoded data for the other browsers.

So why dont you agree with user of the system to select an image from a known folder? Or they can set their choice folder for images.

Most browsers wont support full path but you can get the filename eg "image.png"

Using PHP inbuilt function to encode:

@$picture_base64 = base64_encode( file_get_contents($image_file_name)  );

The sign @ will suppress error if path is not found but the result will be a null for variable $picture_base64 so i guess youre ok with null like i am else do a check for null before proceeding.

In html you can select an image filename to the input e.g. "image.png" ( but not the full path)

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

Then in PHP you can do:

$path = "C:\\users\\john\\Desktop\\images\\"
@$picture_base64 = base64_encode( file_get_contents( $path. $_POST['image']);

Then $picture_base64 will be something like

"AQAAAAMAAAAHAAAADwAAAB8AAAA/AAAAfwAAAP8AAAD/AQAA/w"
Related