需求描述
读取本地文件,如果文件内容是Base64,则直接上传;如果不是,加Base64后上传。
测试文件
文件内容是二进制
文件内容是Base64
代码
<div class="avatar-upload">
<h3 style="margin-right:12px;display: inline;">上传文件</h3>
<a @click="uploadFile" >请选择文件</a>
<input type="file" @change="changeFile" id="avatarInput">
</div>
uploadFile(){
$('input[id=avatarInput]').click();
},
isBase64(str){
if(str === '' || str.trim() === ''){
return false;
}
try{
atob(str);
return true;
} catch(err){
return false;
}
},
changeFile(e){
const that = this;
const files = e.target.files;
if (files && files.length) {
const file = files[0];
const reader = new FileReader();
reader.readAsBinaryString(file); // 注意:读取到的是二进制字符串
reader.onload = function(e){
let fileText = e.target.result; // 二进制字符串文本
if(!that.isBase64(fileText)){
fileText = window.btoa(fileText); // 注意:是使用btoa对"二进制字符串"进行Base64编码
} else {
fileText = fileText.replace(/\r\n/g,""); // 直接读取出的Base64文件内容可能有\r\n,将其替换掉
}
ajaxImportData({"Param":fileText}).then(res=>{
// ...
});
document.getElementById('avatarInput').value = null;
}
};
}
扩展:FileReader.readAsDataURL
使用FileReader.readAsDataURL读取出的文件格式如下:
data:application/octet-stream;base64,MIIL6DCCCZEwHBYCRVMCAQEWE0luZm9zZWNfT
这里是对读取出的文件直接计算Base64,但如果文件内容本身就是Base64的,这里还是会多做一次Base64计算。