https://www.jianshu.com/p/bee8c393c422 感謝
使用了element ui,願望是 選擇圖片文件之后,不立即上傳,先顯示預覽圖,點擊上傳按鈕之后再上傳,element版本是2.13
用到了 URL.createObjectURL(file.raw)
html
<el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" ref="upload" :show-file-list="false" :auto-upload="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-change="onchange" > <img v-if="form.img" :src="form.img" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> <el-button type="success" style="margin-left: 10px;" @click="upimg">上傳</el-button>
js
onchange:function(file,filelist){
let fileName = file.name;
let regex = /(.jpg|.jpeg|.gif|.png|.bmp)$/;
if (regex.test(fileName.toLowerCase())) {
// console.log(URL.createObjectURL(file.raw))
Vue.set(this.form,"img",URL.createObjectURL(file.raw))//新版本需要這么做,老版本好像file或者filelist里面直接就有url,使用Vue.set是應為需要重新渲染
} else {
this.$message.error('請選擇圖片文件');
}
}
接着是圖片轉為base64,一下和上面的無關,就是搜到了在這里做個記錄
function img264(imgUrl){ let that = this window.URL = window.URL || window.webkitURL; var xhr = new XMLHttpRequest(); xhr.open("get", imgUrl, true); // 至關重要 xhr.responseType = "blob"; xhr.onload = function () { if (this.status == 200) { //得到一個blob對象 var blob = this.response; console.log("blob", blob) // 至關重要 let oFileReader = new FileReader(); oFileReader.onloadend = function (e) { let base64 = e.target.result; console.log("方式一》》》》》》》》》", base64) // that.form.img = base64 that.$set(form,"img",base64) }; oFileReader.readAsDataURL(blob); } } xhr.send(); }