How do I upload image in vuejs?
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) } ) }}
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 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>