简体   繁体   中英

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. It's like not sending anything.

When I try Postman or Insomnia it works perfectly fine.

My Laravel Controller is like this:

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 returns A file was sent! , white Angular returns No file sent!

My Courses.component.ts is like this:

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

And my Courses.component.html is like this:

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

I am new to Angular, so I have been stuck here for quite some time.

Try to use enctype instead of Content-Type

So Replace your:

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

by

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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