I want to send text and an image to a blog post API endpoint that accept a text (required ) and an image ( optional ). I am able to POST a new blog post when I fill in a textarea only but unable to send an image in the POST body. Here's the form fields
<label for="comment" class="sr-only">Write what's on your mind</label>
<textarea
v-model="form.post"
rows="3"
name="comment"
></textarea>
<label>
<input ref="file" type="file" v-on:change="onImageUpload(e)" />
</label>
In my script setup
<script setup>
import { ref } from "vue";
const form = ref({
post: null,
file: null
});
function onImageUpload() {
console.log(file.value.files);
// form.value.file = form.value.file[0];
// console.log("selected file", form.value);
}
</script>
This code returns the error below
Uncaught ReferenceError: file is not defined
How can I access the image file being uploaded and pass it along inside the form.value?
My way of handling file input is that I receive the file from onChange of the input. And store the file as a state in data
This is how I implement.
<input
@change="handleFileInput"
type="file"
accept="image/jpeg, image/png"
/>
data: () => ({
file: null,
}),
methods: {
handleFileInput(e) {
this.file = e.target.files[0];
}
}
In your code, you tried to pass e from onChange, but you don't need to do this for just passing event object. Try adding a parameter that accept the event object and use that object to get access to chosen files. This might be different from your approach with refs, but it just works.