使用AJAX将PDF作为base64文件上传到服务器 [英] Upload PDF as base64 file to the server using AJAX
本文介绍了使用AJAX将PDF作为base64文件上传到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我想将以下信息上传到服务器:
Say I want to upload the following information to a server:
var info = {
name: "John",
age: 30,
resume: resume.pdf // base64 String
};
我的 AJAX
调用可能看起来像这样:
My AJAX
call might look something like this:
$.ajax({
url: "http://example.com",
type: "POST",
dataType: "JSON",
data: info,
success: function (response){
// do something
}
});
我的问题是如何修改 AJAX
调用以将 resume.pdf
文件(resume属性)作为base64字符串上载到服务器?
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]);
});
这篇关于使用AJAX将PDF作为base64文件上传到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文