Good evening, I'm uploading file, it's working but every time I upload the file the page refreshes, could anyone give a hint how to solve this? I'm using angular 5.
component.ts
OnSubmit(){
const formData = new FormData();
const files: Array<File> = this.filesToUpload;
for(let i =0; i < files.length; i++){
formData.append("files[]", files[i], files[i]['name']);
formData.append('title' , this.form.get('title').value);
}
this.imageService.postFile(formData).subscribe(data=>{
// Check if comment was saved to database or not
if (!data.success) {
this.messageClass = 'alert alert-danger'; // Return error class
this.message = data.message; // Return error message
toast("Erro ao salvar", 4000);
} else {
this.messageClass = 'alert alert-success'; // Return success class
this.message = data.message; // Return success message
toast("Comentário criado!", 2000);
setTimeout(() => {
this.form.reset(); // Reset all form fields
}, 1000);
// Clear form data after two seconds
}
});
}
fileChangeEvent(fileInput: any) {
this.filesToUpload = <Array<File>>fileInput.target.files;
// Show image preview
var reader = new FileReader();
reader.onload = (event:any) => {
this.imageUrl = event.target['result'];
}
reader.readAsDataURL(fileInput.target.files[0]);
console.log(fileInput)
}
component.html
<form [formGroup]="form" (ngSubmit)="OnSubmit()">
<div class="form-group col-md-4">
<label for="title">Title :</label>
<input id="title" placeholder="Title" formControlName="title">
</div>
<img [src]="imageUrl" style="width:250px;height:200px">
<input type="file" (change)="fileChangeEvent($event)" placeholder="Upload a file..." multiple/>
<button type="submit" >Submit</button>
</form>
service.ts
postFile(formData) {
let headers = new Headers(); // Create headers
return this.http.post(this.domain + '/postFile', formData)
.map(res => res.json())
}