繁体   English   中英

将文件从 Angular 发送到 Laravel

[英]Sending file from Angular to Laravel

I'm sending an image file from Angular 13.0.4 to my Laravel 8 controller, but this file is not recognized by 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 的新手,所以我被困在这里很长一段时间了。

尝试使用enctype而不是Content-Type

所以替换你的:

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

经过

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

暂无
暂无

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

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