Angular - Excel upload not uploading any file to the backend

Viewed 187

I am using Angular-12 and Laravel-8 to upload Excel file to the DB:

Laravel:

public function importStudent(Request $request)
{
try {
    $user = Auth::user()->id;
    $validator = Validator::make($request->all(), [
        'document' => 'file|mimes:xlsx|max:10000',
    ]);
    if($validator->fails()) {
        return $this->error($validator->errors(), 401);
    } else {
        $check = User::where('id', $user)->pluck('id');
        if($check[0] !== null || $check[0] !== undefined) {

            $file = $request->file('document');
            $file->move(public_path('storage/file_imports/student_imports'), $file->getClientOriginalName());
            Excel::import(new StudentImport, public_path('storage/file_imports/student_imports/' . $file->getClientOriginalName() ));
            return $this->success('Students Successfully Imported.', [
                'file'         => $file
            ]);
        } else {
            return $this->error('Not allowed', 401);
        }
    }
    } catch(\Exception $e) {
        return $this->error($e->getMessage());
    }
}

Angular:

service:

importStudent(file: File): Observable < HttpEvent < any >> {
  const formData: FormData = new FormData();

  formData.append('document', file);
  const params = new HttpParams();
  const headers = new HttpHeaders().set('Authorization', this.token.get());

  const options = {
    headers,
    reportProgress: true,
  };

  const req = new HttpRequest('POST', this.api.baseURL + 'students/import', formData, options);

  return this.http.request(req);
}

component:

currentFile ? : File;
progress = 0;
message = '';
importForm!: FormGroup;

constructor(
  private fb: FormBuilder,
  private studentService: StudentService,
) {}

ngOnInit(): void {
  $(function() {
    bsCustomFileInput.init();
  });
  this.loadImportForm();
}

loadImportForm() {
  this.importForm = this.fb.group({
    document: ['', [
      Validators.required,
      RxwebValidators.extension({
        extensions: ["xlsx"]
      })
    ]],
  });
}

get f() {
  return this.importForm.controls;
}

selectFile(event: any): void {
  this.selectedFiles = event.target.files;
}

onSubmit() {
  this.isSubmitted = true;
  this.isLoading = true;
  this.progress = 0;

  if (this.importForm.invalid) {
    return;
  }

  if (this.selectedFiles) {
    const file: File | null = this.selectedFiles.item(0);
    if (file) {
      this.currentFile = file;
      console.log(this.currentFile);

      this.studentService.importStudent(this.currentFile).subscribe(
        (event: any) => {
          if (event.type === HttpEventType.UploadProgress) {
            this.progress = Math.round(100 * event.loaded / event.total);
          } else if (event instanceof HttpResponse) {
            this.message = event.body.message;
          }
        },
        (err: any) => {
          this.progress = 0;
          this.isLoading = false;

          if (err.error && err.error.message) {
            this.message = err.error.message;
          } else {
            this.message = 'Could not upload the file!';
          }
          this.currentFile = undefined;
        });
    }
    this.selectedFiles = undefined;
  }
}

HTML:

<form method="post" [formGroup]="importForm" (ngSubmit)="onSubmit()" enctype='multipart/form-data'>
  <div class="modal-body">
    <div class="custom-file">
      <input type="file" formControlName="document" name="document" (change)="selectFile($event)" class="custom-file-input" id="customFile" accept=".xlsx" required="required">
      <label class="custom-file-label" for="exampleInputFile">Choose Excel File: .xlsx</label>
    </div><br/><br/>

    <div *ngIf="(isSubmitted && f.document.errors) || (f.document.touched && f.document.invalid)" class="invalid-feedback">
      <div *ngIf="f.document.hasError('required')">File is required</div>
      <div *ngIf="f.document.hasError('extension')">
        <div class="text-danger">
          Enter valid File Type!
        </div>
      </div>
    </div>
    <div *ngIf="currentFile" class="progress my-3">
      <div class="progress-bar progress-bar-info progress-bar-striped" role="progressbar" attr.aria-valuenow="{{ progress }}" aria-valuemin="0" aria-valuemax="100" [ngStyle]="{ width: progress + '%' }">
        {{ progress }}%
      </div>
    </div>
    <div *ngIf="message" class="alert alert-secondary" role="alert">{{ message }}</div>
  </div>
  <div class="modal-footer">
    <button [disabled]="isLoading" type="submit" class="btn btn-success"><span *ngIf="isLoading" class="spinner-border spinner-border-sm mr-1"></span><i class="fas fa-plus-square"></i> Upload</button>
  </div>
</form>

When I submitted, it displays success, but nothing at the backend.

I did console.log(this.currentFile); but it's not showing anything.

What could be wrong and how do I resolve it?

Thanks

0 Answers
Related