Angular файл Загрузить передаваемое изображение как [объектный файл] - PullRequest
1 голос
/ 20 января 2020

Я создал реактивную форму в Angular и пытаюсь загрузить изображение через нее. Предполагается загрузить изображение в указанную папку c и вернуть imageUrl в базу данных. Но вместо получения url изображение передается в базу данных как [объектный файл] , и в директиве изображение не загружается. Пожалуйста, посмотрите на мой код ниже:

HTML КОД:

<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 Компонент:

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(['/']);
    })
}

Сервисный код:

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 Ответ

0 голосов
/ 22 января 2020

Вот пример того, как вы можете загрузить файл в angular, этот пример включает индикатор выполнения, если вам нужен

компонент. 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 {}

Вот живой пример, проверьте это: https://stackblitz.com/edit/angular-upload-file-with-progress-bar

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...