Angular 角度文件上传传递图像为[对象文件]

Angular 角度文件上传传递图像为[对象文件],angular,file-upload,angular-reactive-forms,angular-file-upload,Angular,File Upload,Angular Reactive Forms,Angular File Upload,我在Angular中创建了一个反应表单,并试图通过它上传图像。它应该将图像上载到特定文件夹,并在数据库中返回imageUrl。但是图像不是作为url获取的,而是作为数据库中的[object File]传递的,并且指令中没有上载图像。请查看下面我的代码: HTML代码: <div class="form-group form-row col-md-9"> <label>Upload Image</label> <inp

我在Angular中创建了一个反应表单,并试图通过它上传图像。它应该将图像上载到特定文件夹,并在数据库中返回imageUrl。但是图像不是作为url获取的,而是作为数据库中的[object File]传递的,并且指令中没有上载图像。请查看下面我的代码:

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>
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;
  }
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();
  }
}
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 {}
服务代码:

<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>
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;
  }
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();
  }
}
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 {}
publiccreateblog(formData):可观察{
console.log(formData.get('imagePath'))
const params=新的HttpParams()
.set('imagePath',formData.get('imagePath'))
让myResponse=this.\u http.post('http://localhost:4000/api/v1/blogs“+”/create?authToken=“+Cookie.get('authToken'),参数);
返回myResponse;
}

下面是一个如何以angular方式上载文件的示例,如果需要,此示例包括进度条

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>
app.module.ts:

<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>
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;
  }
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();
  }
}
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 {}

这里是一个实时示例检查它:

这里是一个如何在angular中上载文件的示例,如果需要,此示例包括进度条

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>
app.module.ts:

<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>
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;
  }
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();
  }
}
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 {}

这里有一个活生生的例子,请检查:

你试过我的例子吗?你试过我的例子吗?