圖片實作base64上傳
- 實作背景
- 實作方式
- 實作代碼
實作背景
圖片上傳一般都是通過呼叫檔案上傳介面,回傳圖片地址,我們用拿到的圖片地址進行相應操作,如表單提交等;
但是最近有一個朋友遇到了一個問題,他們沒有做圖片管理,所以需要前端將圖片轉換為base64的形式進行上傳. 將圖片轉化為base64,然后提交這個轉換后的字串.
下面做了一個上傳圖片后隱藏上傳按鈕,可以預覽,可以洗掉的功能.
實作方式
通過element-ui 提供的upload方法進行上傳,獲取上傳的file檔案,進行轉化,提交
實作代碼
html代碼
<div class="main">
<el-upload
:class="{ hide: hideUploadEdit }"
action=""
:on-change="getImageFile"
:on-remove="handlePicRemove"
:on-preview="handlePicPreview"
:limit="1"
list-type="picture-card"
:auto-upload="false"
>
<i class="el-icon-plus"></i>
</el-upload>
<div class="martop">下面是用來回顯的圖片</div>
<el-image :src="imageUrl" class="imgwidth">
<div slot="error" class="image-slot">
<i class="el-icon-picture-outline"></i>
</div>
</el-image>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="" />
</el-dialog>
</div>
</template>
js代碼
<script>
export default {
data() {
return {
imageUrl: "",
fileList: [],
dialogImageUrl: "",
dialogVisible: false,
hideUploadEdit: false, // 是否隱藏上傳按鈕
};
},
methods: {
// 獲取圖片資訊
getImageFile(file, fileList) {
console.log("fileList", fileList);
this.getImageBase64(file.raw).then((res) => {
console.log("res", res);
this.imageUrl = res;
});
// 大于1張隱藏
this.hideUploadEdit = fileList.length >= 1;
},
//轉換成base64方法
getImageBase64(file) {
return new Promise(function (resolve, reject) {
let newImagereader = new FileReader();
let imgInfo = "";
newImagereader.readAsDataURL(file);
newImagereader.onload = function () {
imgInfo = newImagereader.result;
};
newImagereader.onerror = function (error) {
reject(error);
};
newImagereader.onloadend = function () {
resolve(imgInfo);
};
});
},
//洗掉
handlePicRemove(file, fileList) {
this.hideUploadEdit = fileList.length >= 1;
this.imageUrl = "";
},
//預覽
handlePicPreview(file) {
console.log("file", file);
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
},
};
</script>```
**css**
```css
.main {
width: 400px;
height: 500px;
}
.martop {
margin-top: 20px;
}
.imgwidth {
width: 100px;
height: 100px;
}
.image-slot {
width: 100px;
height: 100px;
}
.image-slot i {
font-size: 100px;
}
.hide .el-upload--picture-card {
display: none;
}
實作效果
上傳前:

上傳后

預覽時

洗掉后

這樣就可以實作效果了,這是一個比較簡單的demo,各位可以根據自己專案進行修改.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/303065.html
標籤:其他
上一篇:陣列的方法
下一篇:webpack學習筆記
