Я недавно пытался загрузить PDF-файлы, используя Angular 8, и отправить данные в laravel бэкэнд.
Но, что интересно, другие входные данные успешно достигают серверной части, за исключением файла.
pu sh -book.component. html
<form (ngSubmit) ="pushBook()" class="form" enctype="multipart/form-data">
<div>
<input (change)="onFileSelected()" type="file" id="file" required>
</div>
<div class="cover-viewer">
<pdf-viewer [src]="pdfSrc"
[render-text]="true"
[page]="page"
[show-all]="false"
style="display: block; width: 500px; height: 200px;">
</pdf-viewer>
</div>
<div class="form-group">
<button class="btn btn-danger" id="upload_book">Upload Book</button>
</div>
</form>
pu sh -book.component.ts
import { Component, OnInit, EventEmitter, Output, ElementRef, ViewChild } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import {MatSnackBar} from '@angular/material/snack-bar';
import {FormBuilder, FormGroup} from '@angular/forms';
import { PdfService } from '../services/pdf.service';
import { Book } from './book.model';
import { FileUploader, FileSelectDirective } from 'ng2-file-upload';
import { DataService } from '../services/data.service';
import * as html2canvas from "html2canvas";
@Component({
selector: 'app-push-book',
templateUrl: './push-book.component.html',
styleUrls: ['./push-book.component.scss']
})
export class PushBookComponent implements OnInit {
input_message: string;
pdfSrc:string = '';
book = new Book();
onFileSelected() {
let file: any = document.querySelector("#file");
if(typeof (FileReader) !== 'undefined') {
let reader = new FileReader();
reader.onload = (e:any) => {
this.pdfSrc = e.target.result;
}
reader.readAsArrayBuffer(file.files[0]);
}
this.book.bookFile = file.files[0];
console.log(this.book.bookFile)
setTimeout(()=> {
let testCanvas: any =document.querySelector('#page1');
let _bookCover = testCanvas.toDataURL();
this.book.bookCover = _bookCover;
}, 5000);
}
constructor( private elementRef: Ele[enter image description here][1]mentRef, private pdfService: PdfService, private snackBar: MatSnackBar, private dataService: DataService) {}
ngOnInit() {
this.pdfSrc = this.pdfService.getPDF();
console.log(this.book)
}
pushBook(){
this.openSnackBar('Loading', '')
this.dataService.uploadBook(this.book).subscribe(res => {
this.openSnackBar('Upload Successfull', 'OK')
}, err => {
this.openSnackBar('Upload Failed', 'Try Again')
})
}
openSnackBar(message: string, action: string){
this.snackBar.open(message, action, {
duration: 3000,
verticalPosition: 'top'
})
}
}
data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private httpClient: HttpClient) { }
//Push a book
uploadBook(data){
return this.httpClient.post("http://192.168.0.38:8000/api/book", data);
}
}
В моей форме я могу утешить загруженный файл. Но в Laravel Backend файл пуст