首页 > 解决方案 > Laravel 无法读取表单数据

问题描述

我正在制作一个网络应用程序,在前端使用 angular,在后端使用 laravel。但是当我尝试将一些数据上传到 laravel API 时,我遇到了一些问题。

我在 Angular 上使用 formdata,因为我需要它来上传文件。但是当我将数据发送到 Laravel 时,它没有通过验证,因为 Laravel 正在获取空数据。

这是提交时调用的函数。

  onUpload() {
    const fd = new FormData;
    fd.append('video', this.video);
    fd.append('image', this.image);
    fd.append('title', 'Hello world');
    fd.append('description', 'Hello world');
    fd.append('userId', '1');
    fd.append('categoryId', '1');

    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    this.http.post('here goes the real url', fd, {
      headers: headers
    }).subscribe(event => {
        console.log(event);
    });
  }

这是我在 Laravel 上的验证器。

    public function rules(){
        $datos = $this->validationData();
        return [
            "description" => ["max:2000"],
            "video" => ["required", "mimes:mp4,mov,ogg"],
            "image" => ["required", "image", "mimes:jpg,jpeg,png,gif,webp"],
            "title" => ["required","min:4", "max:100"],
            "userId" => ["required", "numeric"],
            "categoryId" =>["numeric"]
        ];
    }

而且,这是错误消息:

errors:
image: ["The image field is required."]
title: ["The title field is required."]
video: ["The video field is required."]
userId: ["The user id field is required."]
__proto__: Object
message: "The given data was invalid."

我需要 Laravel 上的额外内容来读取数据吗?还是我上传错了?非常感谢您的时间。

标签: phpangularlaravel

解决方案


尝试更改Content-typemultipart/form-data

const headers = new HttpHeaders({
      'Content-Type': 'multipart/form-data'
});

推荐阅读