【问题标题】:VueJS Laravel - Uploading image using Axios post error: 'The given data was invalid'VueJS Laravel - 使用 Axios 上传图片发布错误:“给定数据无效”
【发布时间】:2020-09-01 04:06:34
【问题描述】:

为了学校,我正在和一些人一起制作博客,现在我想将图片上传到博客文章中。但是后来这个上传帖子出错了:

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

我在互联网上搜索并查看了其他对话,但找不到我的解决方案。 这是我的代码:

这是 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>

组件中的脚本:

<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);
            });


        }
    },
}

以及我正在使用的控制器功能:

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!']);
    }
}

我该如何解决这个问题?

【问题讨论】:

    标签: javascript php laravel vue.js axios


    【解决方案1】:

    您可以使用image 规则(验证文件为jpeg、png、bmp、gif、svg 或webp)或使用mimes:jpeg,png,jpg,gif,svg

    所以您的验证将是:

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

    或者:

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

    此外,file 规则检查字段是否是成功上传的文件,max:2048 规则检查文件大小是否小于或等于 2048 千字节 (2MB)。请参阅Laravel docs 了解更多信息。

    在 VueJs 上,您必须将所有输入附加到 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(
        //...
    

    【讨论】:

    • {message: "The given data was invalid.",…} 错误:{image: ["图片必须是文件。", "图片必须是文件类型:jpeg, png, jpg, gif, svg。"]} 消息:"给定的数据无效。"
    • @JensBouma 你有没有像上面那样改变你的js?您的文件可能已损坏,请尝试使用另一个文件。
    • 是的,我已经改过了。当我上传带有 .png 扩展名的文件时,它仍然给出错误“图像必须是文件类型:jpeg、png、jpg、gif、svg”
    • Nvm 我在一个地方使用了 imge 而不是 image
    • @HafezDivandari 这对我有用。起初我试图在 axios.post 调用中将我的数据作为对象传递,但它没有用。为什么在 Vue.js 中将数据设置为 new FormData 对象?您可以链接有关此的文档吗?很好的答案,谢谢!
    猜你喜欢
    • 2019-09-01
    • 2018-08-05
    • 2020-09-08
    • 2020-12-07
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多