Загрузка файла в угловом формате:
app.component.html
<input #fileUpload type="file" id="fileUpload" style="" (change)="detectFiles($event)" (click)="fileUpload.value = null">
app.component.ts
import { Component } from '@angular/core';
import { HttpEvent, HttpEventType } from '@angular/common/http';
import { FileUploadService } from './fileUpload.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private fileUploadService: FileUploadService) {
}
detectFiles(event) {
if (event.target.files.length == 0) {
console.log("No file selected!");
return
}
let file: File = event.target.files[0];
console.log("FILE DATA:",file);
let uploadPath = "/home/upload/";
this.fileUploadService.uploadFile(uploadPath, file).subscribe((event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Response:
console.log(event.body);
}
});
}
}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { HttpClientModule } from '@angular/common/http';
import { FileUploadService } from './fileUpload.service';
@NgModule({
imports: [ BrowserModule, FormsModule, HttpClientModule],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ],
providers: [ FileUploadService ]
})
export class AppModule { }
fileUpload.service.ts
import { Inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders, HttpRequest } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable()
export class FileUploadService {
constructor(private http: HttpClient) {
}
uploadFile(uploadPath, fileToUpload: File) {
const _formData = new FormData();
_formData.append('file', fileToUpload, fileToUpload.name);
_formData.append('uploadPath', uploadPath);
const url = `api/v1/uploadFile`;
const request = new HttpRequest('POST', url, _formData, {reportProgress: true });
return this.http.request(request);
}
}
См .: https://stackblitz.com/edit/angular-rmpdhr?file=src%2Fapp%2FfileUpload.service.ts