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

 玻璃里的鱼鱼 发布于 2023-01-12 17:37

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

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 个回答
  • 我仍然真的不明白为什么你想这样做,但如果你必须... FileReader浏览器支持.

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

    2023-01-12 17:40 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有