简体   繁体   中英

Upload PDF as base64 file to the server using AJAX

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?

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]);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM