最近在做一個element的upload以base64的方式實現文件上傳,就需要前端處理上傳文件的file文件流。接下來記錄處理過程,僅供參考!
1.使用element的upload組件,選擇你需要的組件就行
<!-- 上傳照片 -->
<div class="uploadPhotoBox">
<el-upload
style="height:126px;width:90px;display:inline-block;"
class="avatar-uploader"
action=''
:on-change="getFile"
:auto-upload="false"
:show-file-list="false"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<img v-else src="../../assets/head.png" style="height:126px;width:90px;"/>
<div class="changePhotoStyle">{{imageUrlText}}</div>
</el-upload>
</div>
2.method裏面處理file生成base64格式,就是getBase64這個函數(FileReader需要使用promise封裝才能使用)
getBase64(file) {
return new Promise(function(resolve, reject) {
let reader = new FileReader();
let imgResult = "";
reader.readAsDataURL(file);
reader.onload = function() {
imgResult = reader.result;
};
reader.onerror = function(error) {
reject(error);
};
reader.onloadend = function() {
resolve(imgResult);
};
});
},
3.通過on-change方式獲取到file的文件信息,然後調用this.getBase64轉換成base64的方式。
getFile(file) {
// if(file.success){
console.log(file)
const isJPG = file.raw.type === 'image/jpeg';
const isPNG = file.raw.type === 'image/png';
const isLt5M = file.raw.size / 1024 / 1024 < 5;
if (!isJPG && !isPNG) {
this.$message.error('上傳圖片只能是JPG或者PNG格式!');
}
if (!isLt5M) {
this.$message.error('上傳圖片大小不能超過 5MB!');
}
if((isJPG || isPNG) && isLt5M){
this.getBase64(file.raw).then(res => {
console.log(res)
//這裏拿到base64的文件流,處理你自己的業務邏輯
});
}
},
以上代碼親測有效,可直接複製到項目中查看console.log打印出來效果,親自動手試試,紙上得來終覺淺,絕知此事要躬行!