简体   繁体   中英

How to upload an Excel file (.xlxs) from Angular front end to Laravel API?

My process starts in this HTML form:

<form [formGroup]="fileForm" enctype="multipart/form-data">
  <input
    type="file"
    accept=".xlsx"
    formControlName="file"
    (change)="onFileChange($event.target.files)"
  />
</form>

When a file is selected, onFileChange() is called, which does the following:

public onFileChange(files: FileList): void {
  if (files.length) {
    this.file = files[0];
  }
}

Once the file is set, the user clicks the upload button:

public onUploadClick(): void {
  if (this.file) {
    this.fileService.uploadFile(this.file).subscribe();
  }
}

My fileService then handles sending the http request to the API:

public uploadFile(file: File): Observable<APIResponse> {
  const url = `${environment.apiURL}/api/other/upload`;

  const formData = new FormData();
  formData.append("file", file, file.name);

  return this.http.post<APIResponse>(url, { formData });
}

Finally, the code in my FileController :

public function upload(Request $request)
{
    dd($request->all()); // Shows as [ "formData" => [] ]

    $file = $request->file('file');
    dd($file); // Shows as null
}

Sorry for the wall of code, but wanted to give you a clear insight into how it currently works.

From what I've found online, using FormData is the right thing to do. I'm pretty sure that part is working correctly, because if I do console.log(formData.get("file")); , it displays the file.

I've also seen a lot about the content-type header. I've tried setting this to undefined , application/json , and also application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (this is the type of the file when it's logged in the console).

On the Laravel side of things, whichever way I try to print the file, it always comes through as [] or null .

Also, there are no errors produced from either Angular or Laravel.

For some context, I'm trying to import the spreadsheet to then use Laravel Excel ( https://docs.laravel-excel.com/ ), so I can import the contents of the spreadsheet into a database (so please let me know if there's an easier way to get to that stage!)

Thanks for any help

In case anyone else runs into this issue, the problem wasn't with the code above.

Turns out it was an issue with my Nginx config file - I had to add

client_max_body_size 0;

to my sites-available config file. This removed the default body size limits, which were causing any files larger than 1mb to not come through to the API.

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