javascript 使用 AJAX 将 PDF 作为 base64 文件上传到服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23923882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload PDF as base64 file to the server using AJAX
提问by Lior Elrom
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
电话可能看起来像这样:
$.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?
我的问题是如何修改AJAX
调用以将resume.pdf
文件(恢复属性)作为 base64 字符串上传到服务器?
回答by Adam Merrifield
I still really don't understand why you'd want to do it this way, but if you must... FileReader Browser Support.
我仍然真的不明白你为什么要这样做,但如果你必须...... FileReader Browser Support。
HTML
HTML
<form>
<input type="file" name="file" id="resume">
<input type="submit">
</form>
Javascript
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]);
});