Upload file in Angular 4
In the my-fileupload.component.ts file
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { FormGroup, FormControl, FormBuilder} from '@angular/forms';
import { SendToService } './_service/service';
@Component({
selector: 'app-my-fileupload',
templateUrl: './app-my-fileupload.component.html',
styleUrls: ['./app-my-fileupload.component.scss'],
providers: [
SendToService
]
})
export class MyFileuploadComponent implements OnInit {
@ViewChild('fileInput') fileInput: ElementRef;
public MyForm : FormGroup;
public Files = new FormControl();
constructor(private fb: FormBuilder, private sendToService:
SendToService){}
ngOnInit() {
this.MyForm = this.fb.group({
Files: this.Files,
});
}
onFileChange(event) {
if (event.target.files.length > 0) {
this.filesToUpload = <Array<File>>event.target.files; // FILE
let size = 5 * 1024 * 1024; // 5MB
for (let i = 0; i < this.filesToUpload.length; i++) {
if (this.filesToUpload.size > 5000000) {
// Message for file size
} else {
this.MyForm.get('Files').setValue(this.filesToUpload);
}
}
}
}
onSubmit(){
const formObj = this.UploadFile.getRawValue();
this.sendToService.UploadFile(formObj).subscribe(response => {
console.log(response) // response = success
if (response == success) {
this.MyForm.reset();
}
}
}
}
In the send-to-service.service.ts file
import { Injectable, OnInit } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
@Injectable()
export class SendToService {
Url_app = 'url';
constructor(private _http: Http) { }
UploadFile(formObj: any) {
let formData = new FormData();
for (let i = 0; i < formObj.length; i++) {
formData.append('Files[]', formObj[i], formObj[i]['name']);
}
return this._http.post( Url_app , formData);
}
}
In the my-fileupload.component.html file
<input id="Files" type="file" #filesInput (change)="onFileChange($event)"
[multiple]="true" />
If you do not want to do this
Use this method
@ViewChild('fileInput') fileInput: ElementRef;
this.filesInput.nativeElement.value = ""
We use ViewChild and ElementRef to access the input