Skip to content

Instantly share code, notes, and snippets.

@rakibulhaq
Forked from dohomi/app.vue
Last active March 10, 2020 22:56
Show Gist options
  • Save rakibulhaq/63308bdf21ecb0aa47982b70ef05c9bd to your computer and use it in GitHub Desktop.
Save rakibulhaq/63308bdf21ecb0aa47982b70ef05c9bd to your computer and use it in GitHub Desktop.
Small file input element based on vuetify
<template>
<div>
<file-input v-model="filename" @formData="formData"></file-input>
<v-btn @click.native="uploadFiles"></v-btn>
</div>
</template>
<script>
import fileInput from './file-input.vue'
export default{
components:{fileInput}
methods:{
uploadFiles(){
// your custom upload method
const form = this.formData
console.log(form)
}
}
}
</script>
<template>
<div>
<v-text-field prepend-icon="attach_file" single-line
v-model="filename" :label="$t(label).toUpperCase()" :required="required"
@click.native="onFocus"
:disabled="disabled" ref="fileTextField"></v-text-field>
<input type="file" :accept="accept" :multiple="multiple" :disabled="disabled"
ref="fileInput" @change="onFileChange"></input>
</div>
</template>
<script>
export default {
props: {
value: {
type: [Array, String]
},
accept: {
type: String,
default: '*'
},
label: {
type: String,
default: 'choose_file'
},
required: {
type: Boolean,
default: false
},
disabled: {
type: Boolean,
default: false
},
multiple: {
type: Boolean,
default: false
}
},
data () {
return {
filename: ''
}
},
watch: {
value (v) {
this.filename = v
}
},
mounted () {
this.filename = this.value
},
methods: {
getFormData (files) {
const forms = []
for (const file of files) {
const form = new FormData()
form.append('data', file, file.name)
forms.push(form)
}
return forms
},
onFocus () {
if (!this.disabled) {
this.$refs.fileInput.click()
}
},
onFileChange ($event) {
const files = $event.target.files || $event.dataTransfer.files
const form = this.getFormData(files)
if (files) {
if (files.length > 0) {
this.filename = [...files].map(file => file.name).join(', ')
} else {
this.filename = null
}
} else {
this.filename = $event.target.value.split('\\').pop()
}
this.$emit('input', this.filename)
this.$emit('formData', form)
}
}
}
</script>
<style scoped>
input[type=file] {
position: absolute;
left: -99999px;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment