说我想将以下信息上传到服务器:
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字符串上传到服务器?
答案 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]);
});