简体   繁体   English

VueJS Laravel - 使用 Axios 上传图像发布错误:“给定数据无效”

[英]VueJS Laravel - Uploading image using Axios post error: 'The given data was invalid'

For school I'm making a blog with some people and now I want to upload an image to the blog post.对于学校,我正在与一些人一起制作博客,现在我想将图片上传到博客文章中。 But then this uploading the post the error:但是随后上传帖子时出现错误:

{message: "The given data was invalid.", errors: {image: ["The image field is required."]}} errors: {image: ["The image field is required."]} message: "The given data was invalid." {message:“给定的数据无效。”,错误:{image:[“图像字段是必需的。”]}}错误:{image:[“图像字段是必需的。”]}消息:“给定的数据无效。”

I have searched on the internet and looked at other conversations, but I can't find my solution.我在互联网上搜索并查看了其他对话,但我找不到我的解决方案。 Here are my codes:这是我的代码:

This is the form in a VueJS component:这是 VueJS 组件中的表单:

<form method="post" action="./api/post" @submit.prevent="createPost()" enctype="multipart/form-data">
    <p>Titel van de post</p>
    <input type="text" placeholder="Titel van de post" name="title" v-model="title">
    <p>Beschrijving bij de post</p>
    <textarea placeholder="Beschrijving bij de post" name="description" v-model="description"/>
    <input type="file" id="image" name="image" ref="image" v-on:change="(e) => {this.onChangeFileUpload(e)}"/>
    <div class="uploadtimer">
        <p>Selecteer een tijd wanneer de post moet worden getoond. (Niet verplicht)</p>
        <datetime format="YYYY-MM-DD H:i" v-model="uploadTime"></datetime>
    </div>
    <input type="submit" class="input-submit">
</form>

The script in the component:组件中的脚本:

<script>
import datetime from 'vuejs-datetimepicker';

export default {
    components: { datetime },
    data() {
        return {
            title: '',
            description: '',
            uploadTime: '',
            image: '',
        }
    },

    methods: {
        onChangeFileUpload(e) {
            this.image = e.target.files[0];
        },
        createPost() {
            let data = new FormData;
            data.append('image', this.image);

            axios.post('./api/post', {
                title: this.title,
                description: this.description,
                data,
                uploadTime: this.uploadTime,

            }).then(response => {

            }).catch(response => {
                document.getElementById('errorMSG').style.display = 'flex';
                document.getElementById('errorMSG').innerHTML = '<span>!</span><p>Er is iets mis gegaan met het plaatsen van de post.</p>';
                setTimeout(function() {
                    document.getElementById('errorMSG').style.display = 'none';
                }, 5000);
            });


        }
    },
}

And the Controller function I'm using:而我正在使用的 Controller function :

public function store(Request $request)
{
    if(Auth::check()) {

        $this->validate($request, [
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg',
        ]);

        $post = new Post();
        $post->title = $request->input('title');
        $post->description = $request->input('description');

        $image = $request->file('image');

        $imageExtension = $image->getClientOriginalExtension();
        $imageName = time() . '_' . $imageExtension;

        $image->move(public_path('/imgs/users-avatars/'), $imageName);

        $post->image = '/imgs/posts-images/' . $imageName;

        $post->uploadTime = $request->input('uploadTime');
        $post->user_id = Auth::User()->id;

        $post->save();

        return (['message' => 'succes']);
    } else {
        return (['message' => 'error', 'handler' => 'Authenticated user is required!']);
    }
}

How can I fix this?我怎样才能解决这个问题?

You may use either image rule (that validates a file to be jpeg, png, bmp, gif, svg, or webp) or use mimes:jpeg,png,jpg,gif,svg :您可以使用任一image规则(验证文件为 jpeg、png、bmp、gif、svg 或 webp)或使用 mimes mimes:jpeg,png,jpg,gif,svg

So your validation would be either:因此,您的验证将是:

'image' => 'required|file|mimes:jpeg,png,jpg,gif,svg|max:2048',

Or:或者:

'image' => 'required|file|image|max:2048',

Additionally, the file rule checks if the field is a successfully uploaded file and max:2048 rule checks if the file size is less than or equal to 2048 kilobytes (2MB).此外, file规则检查该字段是否为成功上传的文件,而max:2048规则检查文件大小是否小于或等于 2048 千字节 (2MB)。 See Laravel docs for more info.有关详细信息,请参阅Laravel 文档

On VueJs, you have to append all your inputs to a FormData :在 VueJs 上,您必须 append 您对FormData的所有输入:

let data = new FormData;
data.append('image', this.image);
data.append('title', this.title);
data.append('description', this.description);
data.append('uploadTime', this.uploadTime);

axios.post('./api/post', data)
    .then(
    //...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM