researchers_'s avatar

Upload image from vue ( Please read me :( @bobbybouwmann )

I have a case where I have to upload image with some input file, let's say I want to post an article with the thumbnail required, so when I try to post image, it always fail, tbh, laravel always is the thumbnail should be required.

this is my vue code.

data() {
    return {
        post: {
            title: '',
            subject: '',
            body: '',
            thumbnail: null,
        },
    }
}

and this is the selected thumbnail event

selectedImage(e) {
    this.post.thumbnail = e.target.files[0];
},

Finally, this is where I store the data

async store() {
    var formData = new FormData();
    formData.append('thumbnail', this.post.thumbnail)
    var data = { ...this.post, thumbnail: this.post.thumbnail  };
    let response = await axios.post('api/posts/create', data)
}

And I got 422 which is

{ 
    "thumbnail": "The thumbnail field is required."
}

I really appreciate who want to help me tonight. It's been 4 hours :(

Maybe @bobbybouwmann @a4ashraf @irsyadadl or even @jeffreyway can help me out. :(

Thanks in advanced.

0 likes
2 replies
eeraertw's avatar

Did you put a correct enctype on the POST request ? When you have elements in your form for the thumbnail you need to set the enctype="multipart/form-data"

yjuyjuy's avatar

try this

async store() {
	var formData = new FormData();
	formData.append('thumbnail', this.post.thumbnail);
	let response = await axios.post('api/posts/create', formData, {
		headers: {
	  	'Content-Type': 'multipart/form-data',
		},
	});
}

Please or to participate in this conversation.