I've created a reactive form in Angular and trying to upload image through it. It is supposed to upload the image to a specific folder and return the imageUrl in the database. But instead of getting it as an url, the image is getting passed as [object File] in the database and no image is uploaded in the directive. Please have a look at my code below:
HTML CODE:
<div class="form-group form-row col-md-9">
<label>Upload Image</label>
<input type="file" id="imagePath" (change)="onSelectedFile($event)" />
<div [innerHTML]="uploadError" class="error"></div>
</div>
Angular Component:
createBlogForm: FormGroup;
public imagePath: string;
constructor(private blogpostService: BlogpostService, private _http: HttpClient, private formBuilder: FormBuilder) { }
ngOnInit() {
console.log("CreateBlogComponent onInIt called");
this.createBlogForm = this.formBuilder.group({
imagePath:['']
})
}
onSelectedFile(event) {
const file = event.target.files[0];
this.createBlogForm.get('imagePath').setValue(file)
console.log(file)
}
public createBlog(): any {
const formData = new FormData();
formData.append('imagePath', this.createBlogForm.get('imagePath').value); }
this.blogpostService.createBlog(formData).subscribe(
data => {
console.log(data);
setTimeout(() =>{
this.router.navigate(['blog', data.blogId]);
}, 1000)
},
error => {
console.log(error);
this.router.navigate(['/']);
})
}
Service code:
public createBlog(formData): Observable<any> {
console.log(formData.get('imagePath') )
const params = new HttpParams()
.set('imagePath', formData.get('imagePath'))
let myResponse = this._http.post('http://localhost:4000/api/v1/blogs' + '/create?authToken=' + Cookie.get('authtoken'), params);
return myResponse;
}
Here is an example how you can upload file in angular, this example includes progress bar if you need
component.html
component.ts:
app.module.ts:
Here is a live example check it: https://stackblitz.com/edit/angular-upload-file-with-progress-bar