【问题标题】:Sending file from Angular to Laravel将文件从 Angular 发送到 Laravel
【发布时间】:2022-01-19 17:05:35
【问题描述】:

我正在从 Angular 13.0.4 向我的 Laravel 8 控制器发送一个图像文件,但该文件无法识别 通过 Laravel。就像什么都不发送一样。

当我尝试 Postman 或 Insomnia 时,它工作得非常好。

我的Laravel Controller是这样的:

public function uploadimage(Request $request)
{
  
  if ($request->hasFile('image'))
  {
        return response()->json(["message" => "A file was sent!"]);
  }
  else
  {
        return response()->json(["message" => "No file sent!"]);
  }
}

Postman 返回文件已发送!,白色 Angular 返回未发送文件!

我的 Courses.component.ts 是这样的:

export class CoursesComponent {
constructor(private http:HttpClient) { }

filedata:any;
/* File onchange event */


fileEvent(e:any){
    this.filedata = e.target.files[0];
}


/* Upload button functioanlity */
onSubmitform(f: NgForm) {

  var myFormData = new FormData();
  const headers = new HttpHeaders();
  headers.append('Content-Type', 'multipart/form-data');
  headers.append('Accept', 'application/json');
  myFormData.append('image', this.filedata);
  /* Image Post Request */
  this.http.post('http://fener.tachyonstudio.com/api/sample-restful-apis', myFormData, {
  headers: headers
  }).subscribe(data => {
   console.log(data);
  });
}

而我的Courses.component.html是这样的:

<form #f="ngForm" (ngSubmit)="onSubmitform(f)" enctype='multipart/form-data'>
  <input type="file"  name="image" (change)="fileEvent($event)"/>
  <button>Upload Image</button>
</form>

我是 Angular 的新手,所以我被困在这里很长一段时间了。

【问题讨论】:

    标签: angular laravel laravel-8


    【解决方案1】:

    尝试使用enctype 而不是Content-Type

    所以替换你的:

    headers.append('Content-Type', 'multipart/form-data');
    

    通过

    headers.append('enctype', 'multipart/form-data');
    

    【讨论】:

      猜你喜欢
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 2020-05-29
      • 2017-01-17
      • 2021-12-17
      • 2021-04-17
      相关资源
      最近更新 更多