I am trying to resize an image before upload, using VueJS.
Something is still a mystery for me: how to work with arrow functions with my other methods' variables?
Here are my issues:
- this.addimage()
doesn't get called (this
doesn't exist).
I tried putting this method inside the function, but then I can't deal with this.
other variables:
for example, this.imgpath
isn't set.
Here is the code. I guess I should use 'file' : reader.readAsDataURL(file);
but don't get it...
<template>
<div>
<div>
<form class="form" v-on:submit.prevent>
<div class="center msb-i" style="font-size: 150%">{{$t('imgupload'))}}
</div>
<div>
<input type="file" v-on:change="onImageChange">
</div>
<img :src="imgpath" :id="mode+'id'">
<div v-if="imgpath!='' && !imageuploaded" class="spinner-border center" role="status">
<span class="sr-only">Loading...</span>
</div>
<div v-if="imageuploaded">{{$t('btn.'+mode+'up')}}</div>
</form>
</div>
</div>
</template>
And here are the methods.
onImageChange(e) {
let files = (e.target.files || e.dataTransfer.files)[0];
let reader = new FileReader();
reader.onload = (e) => {
this.imgpath = e.target.result;
var image = new Image();
image.src = e.target.result;
image.onload = function() {
var maxWidth = 1024,
maxHeight = 1024,
imageWidth = image.width,
imageHeight = image.height;
if (imageWidth > imageHeight) {
if (imageWidth > maxWidth) {
imageHeight *= maxWidth / imageWidth;
imageWidth = maxWidth;
}
}
else {
if (imageHeight > maxHeight) {
imageWidth *= maxHeight / imageHeight;
imageHeight = maxHeight;
}
}
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
image.width = imageWidth;
image.height = imageHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, imageWidth, imageHeight);
// Convert the resize image to a new file to post it.
this.imgpath=canvas.toDataURL("image/"+this.imgext);
**this.addimage(); //HOW TO DO THIS??**
}
};
reader.readAsDataURL(file);
**this.addimage(); //OF COURSE THIS DOESN'T WORK: NOTHING HAS BEEN SET AND IT'S DOING IT BEFORE reader.onload**
}
addimage(){
var path='';
var urlpath="/newpicpath/";
axios.get(urlpath+this.id).then(response => {
path="." + response.data + "."+this.imgext;
axios.post('/uploadfile',{image: this.imgpath, path:path})
})
;
});
},
}
};
</script>