使用AJAX将PDF作为base64文件上载到服务器

时间:2014-05-29 00:20:49

标签: javascript jquery ajax api base64

说我想将以下信息上传到服务器:

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

我的AJAX电话可能看起来像这样:

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

我的问题是如何修改AJAX调用以将resume.pdf文件(resume属性)作为base64字符串上传到服务器?

1 个答案:

答案 0 :(得分:7)

我仍然真的不明白你为什么要这样做,但如果你必须...... 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]);
});