首页 > 解决方案 > 从 Angular 12 到 Laravel 8 api 的 Multipart/form-data 问题

问题描述

我正在尝试将一些字段数据和文件发送到 Laravel 后端。如果我尝试使用 Postman 使用 api,但当我通过 Angular 发送它时总是显示错误,它是有效的

HttpErrorResponse {headers: HttpHeaders, status: 422, statusText: 'Unprocessable Entity', url: 'http://127.0.0.1:8000/api/works', ok: false, …}
    error:
    errors:
    category: ['The category field is required.']
    picture: ['The picture field is required.']
    title: ['The title field is required.']
    title_en: ['The title en field is required.']
    title_uz: ['The title uz field is required.']
    [[Prototype]]: Object
    message: "The given data was invalid."
    [[Prototype]]: Object
    headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
    message: "Http failure response for http://127.0.0.1:8000/api/works: 422 Unprocessable Entity"
    name: "HttpErrorResponse"
    ok: false
    status: 422
    statusText: "Unprocessable Entity"
    url: "http://127.0.0.1:8000/api/works"
    [[Prototype]]: HttpResponseBase

就像 Laravel 没有看到任何必填字段一样。

角函数:

 onSubmit() {

  const formData = new FormData()

   formData.append('title', this.worksForm.get('title')!.value)
   formData.append('title_en', this.worksForm.get('title_en')!.value)
   formData.append('title_uz', this.worksForm.get('title_uz')!.value)
   formData.append('category', this.worksForm.get('category')!.value)
   formData.append('description', this.worksForm.get('description')?.value)
   formData.append('description_en', this.worksForm.get('description_en')?.value)
   formData.append('description_uz', this.worksForm.get('description_uz')?.value)
   formData.append('picture', this.worksForm.get('picture')?.value)


   const headers = new HttpHeaders().append('Content-Type', ['multipart/form-data']);
           
   this.http.post(`${environment.apiUrl}works`, formData,
   {
     headers: headers
   }
   ).subscribe(
    (res) => console.log(res),
    (err) => console.log(err)
       )

   }

Laravel 商店()

public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'title_en' => 'required',
            'title_uz' => 'required',
            'category' => 'required',
            'picture' => 'required'
        ]);

        if ($file = $request->file('picture')) {
            $name = $file->getClientOriginalName();
            $path = $request->file('picture')->storeAs('public/pictures', $name);
            $request['picture'] = $name;

        }
        $input = $request->all();
        $input['picture'] = $name;
        return Work::create($input);
    }

我已经在考虑尝试其他后端......还是我前面有错误?

对于此类问题,我在这里没有找到任何可行的答案。

标签: angularlaravelapimultipartform-data

解决方案


推荐阅读