Please, below is my code in the script section of my vue component.
I\'m getting all the input fields right but the image and video uploads are showing empty values.
I think in your case you are looking for a solution like this
example: uploading a image and previewing it before submission
<template>
<div>
<img src:"previewImage" class="uploading-image" />
<input type="file" accept="image/jpeg" @change=uploadImage>
</div>
</template>
<script>
export default {
name:'imageUpload',
data(){
return{
previewImage:null
}
},
methods:{
uploadImage(e){
const image = e.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(image);
reader.onload = e =>{
this.previewImage = e.target.result;
console.log(this.previewImage);
};
}
}
} // missing closure added
</script>
<style>
.uploading-image{
display:flex;
}
</style>
If you are using axios
or fetch
uploading files with vue is pretty easy.
This is a copy/pasta from my current project. I use axios to upload images:
First you'll need to have your input look like this:
<input type="file" accept="image/*" @change="uploadImage($event)" id="file-input">
Then add a method like this:
methods: {
uploadImage(event) {
const URL = 'http://foobar.com/upload';
let data = new FormData();
data.append('name', 'my-picture');
data.append('file', event.target.files[0]);
let config = {
header : {
'Content-Type' : 'image/png'
}
}
axios.put(
URL,
data,
config
).then(
response => {
console.log('image upload response > ', response)
}
)
}
}
If you want to upload an image and preview it before submission you can use simple and functional way as optionally.
<template>
<input type="file" accept="image/*" @change="onChange" />
<div id="preview">
<img v-if="item.imageUrl" :src="item.imageUrl" />
</div>
</template>
<script>
export default {
name: 'imageUpload',
data() {
return {
item:{
//...
image : null
imageUrl: null
}
}
},
methods: {
onChange(e) {
const file = e.target.files[0]
this.image = file
this.item.imageUrl = URL.createObjectURL(file)
}
}
}
</script>
I'm taking from a few other peoples answers to sum it up.
this.image
is base64 encoded and ready to send to your API.
<template>
<v-file-input
v-model="file"
chips
accept="image/*"
label="Image"
@change="onFileChange"
/>
</template>
<script>
export default {
data: { file: null, image: null },
methods: {
onFileChange() {
const reader = new FileReader()
reader.readAsDataURL(this.file)
reader.onload = e => {
this.image = e.target.result
console.log(this.image)
}
},
},
}
</script>