Angular file Upload passing image as [object File]

1.2k views Asked by At

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;
  }
1

There are 1 answers

0
ferhado On

Here is an example how you can upload file in angular, this example includes progress bar if you need

component.html

<input type="file" (change)="upload($event.target.files[0])">

<div class="progress" *ngIf="progress">
    <div class="progress-bar" [style.width]="progress + '%'">{{progress}}%</div>
</div>

component.ts:

import { Component } from "@angular/core";
import {
  HttpClient,
  HttpEventType,
  HttpErrorResponse
} from "@angular/common/http";
import { map, catchError } from "rxjs/operators";
import { throwError } from "rxjs";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  progress: number;

  constructor(private http: HttpClient) {}

  upload(file) {
    this.progress = 1;
    const formData = new FormData();
    formData.append("file", file);

    this.http
      .post("yout-url-here", formData, {
        reportProgress: true,
        observe: "events"
      })
      .pipe(
        map((event: any) => {
          if (event.type == HttpEventType.UploadProgress) {
            this.progress = Math.round((100 / event.total) * event.loaded);
          } else if (event.type == HttpEventType.Response) {
            this.progress = null;
          }
        }),
        catchError((err: any) => {
          this.progress = null;
          alert(err.message);
          return throwError(err.message);
        })
      )
      .toPromise();
  }
}

app.module.ts:

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { HttpClientModule } from "@angular/common/http";

import { AppComponent } from "./app.component";

@NgModule({
  imports: [BrowserModule, FormsModule, HttpClientModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

Here is a live example check it: https://stackblitz.com/edit/angular-upload-file-with-progress-bar