本文包括選擇圖片在Vue轉Base64,和設置上傳前只能選擇jpg、png格式的圖片
el-upload里面屬性直接看官方API文檔:https://element.eleme.cn/#/zh-CN/component/upload#attribute
1、設置只能選擇jpg和png格式的圖片
<el-upload ref="upload" class="upload-demo" action="" :on-preview="handlePreview" accept=".jpg,.png" :on-remove="handleRemove" :on-change="imgBroadcastChange" :on-success="handleAvatarSuccess" :file-list="fileList" :auto-upload="false" //不立即上傳 :limit=1 //只能選擇一個圖片 > <div class="pic-btn-body"> <el-button slot="trigger" size="small" name="signimg" type="success">選取文件</el-button> <div class="el-upload__tip">只能上傳jpg/png文件</div> </div> </el-upload>
搜索了幾篇文章上說設置 accept=".jpg,.png" ,但是設置 accept 是選擇時只能選擇jpg和png格式的圖片,依舊不能防止某些腦子有問題的,選擇所有文件后再選擇其他格式的圖片,如下圖
此時可以設置 :on-change="imgBroadcastChange" 事件,進行控制,具體方法如下
<script> export default { name: 'AccountChange', data() { return {
SignBase64:"", fileList: [] } }, mounted() { }, methods: { //圖片上傳前判斷 imgBroadcastChange(file) { let testmsg=file.name.substring(file.name.lastIndexOf('.')+1) const isJpg = testmsg === 'jpg' || testmsg === 'png' const isLt2M = file.size / 1024 / 1024 < 2; if (!isJpg) {//圖片格式判斷 this.fileList = this.fileList.filter(v => v.uid !== file.uid) this.$message.error('上傳頭像圖片只能是 JPG 或 PNG 格式!'); } if (!isLt2M) {//圖片大小判斷 this.fileList = this.fileList.filter(v => v.uid !== file.uid) this.$message.error('上傳簽名圖片大小不能超過 2MB!'); } if (isJpg && isLt2M){ this.fileList.push(file) } return isJpg && isLt2M; } } </script>
2、點擊上傳時將圖片轉換為Base64編碼
首先創建utils.js,並把一下代碼直接拷進去
export function uploadImgToBase64 (file) { return new Promise((resolve, reject) => { const reader = new FileReader() reader.readAsDataURL(file) reader.onload = function () { // 圖片轉base64完成后返回reader對象 resolve(reader) } reader.onerror = reject }) }
在頁面進行utils.js引用
import { uploadImgToBase64 } from '@/utils/utils'
點擊保存時把圖片轉換為Base64
// 點擊保存 common_comment_submit() { const imgBroadcastListBase64 = [] if(this.IsReupload){ // 並發 轉碼輪播圖片list => base64 const filePromises = this.fileList.map(async file => { const response = await uploadImgToBase64(file.raw) return response.result.replace(/.*;base64,/, '') // 去掉data:image/jpeg;base64, }) // 按次序輸出 base64圖片 for (const textPromise of filePromises) { imgBroadcastListBase64.push(await textPromise) } } this.SignBase64 = imgBroadcastListBase64.join()
//到這里,已經轉換為base64編碼了,此時直接調用后台接口,把參數傳過去,后台進行保存即可 // this.SignBase64 即為所需上傳圖片的編碼 },