Created
May 9, 2018 17:15
-
-
Save baileylo/4951fc2b152289c013c3ac1fff272404 to your computer and use it in GitHub Desktop.
A vue component for uploading images and previewing them.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div> | |
<div> | |
<div class="rounded" style="background-color:white; border: 1px solid #999; height: 200px;font-size:128px;text-align:center" @drop.stop.prevent="drop" @dragenter.stop.prevent="dragEnter" @dragleave.stop.prevent="dragLeave" @dragover.stop.prevent=""> | |
<img :src="imageData" v-if="imageData" ref="preview" :width="imageWidth" :height="imageHeight"> | |
<i class="fas fa-image" v-else="imageData"></i> | |
</div> | |
</div> | |
<input type="file" ref="fileInput" class="form-control d-none" v-bind:class="{'is-invalid': error}" @change="onFileChange"> | |
<div class="invalid-feedback" :class="{'d-block': error}" v-text="error" v-if="error"></div> | |
</div> | |
</template> | |
<script> | |
export default { | |
methods: { | |
dragEnter(e) { | |
this.over_drop_zone = true; | |
}, | |
dragLeave(e) { | |
this.over_drop_zone = false; | |
}, | |
drop(e) { | |
this.$refs.fileInput.files = e.dataTransfer.files; | |
}, | |
onFileChange(e) { | |
const max_file_size = 10000000; | |
const files = e.target.files || e.dataTransfer.files; | |
const image = files[0] || false; | |
this.error = ''; | |
if (!image) { | |
return; | |
} | |
if (image.size > max_file_size) { | |
this.error = 'File must be less than 10 megabytes' | |
this.$refs.fileInput.value = null; | |
} | |
if (image.type !== 'image/jpg' && image.type !== 'image/png' && image.type !== 'gif' && image.type !== 'image/jpeg') { | |
const image_type = image.type.split('/')[1] || 'unknown'; | |
this.$refs.fileInput.value = null; | |
this.error = `File must either be jpg, png, or gif, got ${image_type}` | |
} | |
const reader = new FileReader(); | |
reader.onload = (e) => { | |
const imageData = e.target.result; | |
const hiddenImage = new Image(); | |
hiddenImage.src = imageData; | |
hiddenImage.onload = (e) => { | |
if (hiddenImage.width < hiddenImage.height) { | |
this.imageWidth = '100%'; | |
this.imageHeight = 'auto'; | |
} else { | |
this.imageWidth = 'auto'; | |
this.imageHeight = '100%'; | |
} | |
console.log('width: ', hiddenImage.width); | |
console.log('height: ', hiddenImage.height); | |
console.log(hiddenImage); | |
this.imageData = imageData; | |
}; | |
this.imageData = e.target.result; | |
}; | |
reader.readAsDataURL(image); | |
} | |
}, | |
data: function () { | |
return { | |
imageHeight: 0, | |
imageWidth: 0, | |
file: '', | |
imageData: '', | |
error: '', | |
over_drop_zone: false | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment