Correct way to upload a PDF with Vue/Axios Hi,
I know how to save an image but I am struggling to save a pdf. So far I have a parent component
<PdfUpload @loaded="onImageUpload" />
data() {
return {
formData: new FormData(),
}
},
methods: {
async onImageUpload(pdf) {
this.formData.append('pdf', pdf);
await axios.post(`/materials/upload/${this.material.SKU}`, this.formData)
.then( res => {
console.log(res.data);
})
},
and in the child I have
<template>
<input type="file" accept="application/pdf,application/vnd.ms-excel" class="fileinput" @change="onChange">
</template>
<script>
export default {
methods: {
onChange(e) {
console.log(e);
if (! e.target.files.length) return;
let file = e.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = e => {
let src = e.target.result;
};
}
}
}
</script>
However when I try to return the data from my controller I get
{pdf: "undefined"}
Why are you reading the contents of a PDF file; this is the type of work you would do to display a preview of an image?
Your onChange method serves no purpose in its current form - you do not emit a loaded event up to the parent component so there is nothing (I can see) to trigger the onImageUploaded method in the parent.
Ahh I was just trying to reuse the image code, but I thought it might be irrelevant. So I shouldn't turn it into a reader at all and just use the file?
The purpose of the Reader was to preview the image hence the assignment to src - so no, not relevant to PDF.
You probably could reduce this down to a single component, e.g.
<input type="file"
accept="application/pdf,application/vnd.ms-excel"
class="fileinput"
@change="onChange"
>
data() {
//
},
methods: {
async onChange(e) {
let file = e.target.files[0];
let formData = new FormData();
formData.append('pdf', file);
await axios.post(`/materials/upload/${this.material.SKU}`, formData)
.then( res => console.log(res.data) )
},
}
@tykus Amazing,
Thank you so much!
No worries @chrisgrim - consider marking the Best Reply above
Hi, Did you add to the form the enctype attribute?
<form method="post" enctype="multipart/form-data">
Please sign in or create an account to participate in this conversation.