4

Say I want to upload the following information to a server:

var info = {
    name: "John",
    age: 30,
    resume: resume.pdf  // base64 String
};

My AJAX call might look something like this:

$.ajax({
    url: "http://example.com",
    type: "POST",
    dataType: "JSON",
    data: info,
    success: function (response){
        // do something
    }
});

My question is how to modify an AJAX call to upload the resume.pdf file (resume property) as base64 String to the server?

Lior Elrom
  • 19,660
  • 16
  • 80
  • 92

1 Answers1

9

I still really don't understand why you'd want to do it this way, but if you must... FileReader Browser Support.

HTML

<form>
  <input type="file" name="file" id="resume">
  <input type="submit">
</form>

Javascript

$('form').on('submit', function (e) {
    e.preventDefault();

    var reader = new FileReader(),
        file = $('#resume')[0];

    if (!file.files.length) {
        alert('no file uploaded');
        return false;
    }

    reader.onload = function () {
        var data = reader.result,
            base64 = data.replace(/^[^,]*,/, ''),
            info = {
                name: "John",
                age: 30,
                resume: base64 //either leave this `basae64` or make it `data` if you want to leave the `data:application/pdf;base64,` at the start
            };

        $.ajax({
            url: "http://example.com",
            type: "POST",
            dataType: "JSON",
            data: info,
            success: function (response) {}
        });
    };

    reader.readAsDataURL(file.files[0]);
});
Adam Merrifield
  • 10,307
  • 4
  • 41
  • 58
  • An API requirement is to upload a local PDF file as base64. Can you change your code so it will read an existing pdf file from the server instead from a user form? – Lior Elrom May 29 '14 at 00:57
  • @Lior so you want to pull a PDF file off a user's local system, turn it into base64, and sent it to a server? Without user interaction (like having an input file for the user to select which file they want to upload) this is not possible. I hope you can see and understand the security vulnerability in this idea. – Adam Merrifield May 29 '14 at 01:00
  • 1
    Thanks for this. Modern frameworks like Angular work best with JSON as far as I see. Handling other types of requests seems to create a code-mess. Certainly this is not the best way in terms of performance, but this should have been thought by the people designing the web standards. Devs should not go back to the stone age just because people refuse to slay sacred standard-cows of theirs (or extend them in a reasonable manner). I know.. I want too much.. – user2173353 Nov 25 '14 at 09:28