It's a normal task to upload a file from the front-end to the back-end. And every developer tried it. Posting a file with a form data type request is a normal way. But what if we want to show a image before upload it to the server? We have an image box and we want to show it to the user before save it.
I found a solution base on base64. I convert the image to base64 and assign it to a variable and connect the image box to present it. Also we can upload base64 to the server and there we convert it to binary image format and save it!
In VueJS, I using the watch to monitor changes on the image field that a user use to select a image, and after user choose a image, front-end app convert it to a base64 string and store it into another variable that connected to the image box.
Let check them in code. At first, I'll define two variable:
- image: connected to file input
- base64: to keep result of conversion
image: function (newVal, oldVal) {
if(newVal) {
this.createBase64Image(newVal);
} else {
this.base64 = null;
}
}
createBase64Image: function(FileObject) {
const reader = new FileReader();
reader.onload = (event) => {
this.base64 = event.target.result;
}
reader.readAsDataURL(FileObject);
}
No comments:
Post a Comment