如何从输入文件.pdf中获取字符串Base64。
我有这个功能,但我没有返回字符串base64。
extencion接受的文件是.pdf
我需要变量的基础64
我的代码:
<input type="file" id="files" name="files" multiple>
Js代码
var base64 = getBase64(document.getElementById('files').files[0])
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
return(reader.result); //THIS NO RETURN NOTHING. WHY?
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
答案 0 :(得分:0)
我测试了它,它有效,你必须在更改事件上添加它,你在任何东西出现之前调用getbase64:
https://jsfiddle.net/ibowankenobi/fcgL3dn8/
document.getElementsByTagName("input")[0].addEventListener("change",getBase64,false);
var _file;
function getBase64() {
var file = this.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
_file = reader.result;
//don't do the below. It is pointless. Either assign the result to a variable within scope or call a callback
//return(reader.result); //THIS NO RETURN NOTHING. WHY?
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}