如何在角度2中上传图像发布方法?

时间:2018-04-17 11:57:04

标签: angular angular2-template angular2-forms

HTML

 <form #productForm="ngForm" ngSubmit)="createNewProduct(productForm)">
   <div class="form-group ">
      <input   type="file" [(ngModel)]="model.files" name="files" #files="ngModel" class="form-control"  id="files"  multiple="">
        </div>
        <div class="form-group ">
            <label for="productname">Name</label>          
             <input type="text" class="form-control" id="productname" required minlength="5" pattern="^[a-zA-Z0-9/,-. ]*$" maxlength="30"  [(ngModel)]="model.productname" name="productname" #productname="ngModel">
        </div>
        <div class="form-group ">
           <label for="sales">Sales price/rate</label>
           <input type="text" class="form-control" id="sales" pattern="[0-9]+" required minlength="0" maxlength="10"  [(ngModel)]="model.sales" name="sales" #sales="ngModel">
       </div>

提交         

component.ts

    createNewProduct(productForm: NgForm) {      
         this.productService.save_user(json).subscribe(response => console.log('Inserted Successfully'),
      error => console.log(error));
  }

service.ts

  save_user(product_data: any): Observable<any[]> {
    const httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
        }),
    };
    return this.http.post('http://localhost:8000/product/', product_data, httpOptions)
        .map(response => response)
        .catch(error => Observable.throw(error.statusText));
};

这里我提到了我的component.ts和service.ts以及我的Html。我不知道如何上传图片。

1 个答案:

答案 0 :(得分:1)

试试这个。在您的服务方法中,创建一个新的formData对象并将文件附加到该对象。然后你可以使用http.post方法将它发送到后端。

public uploadFile(file: File, otherData: any): Observable<any> {

  let formData:FormData = new FormData();  
  formData.append('document',file);
  formData.append('name',otherData.name);
  formData.append('age',otherData.name);  

  return this.http.post("/your/url",formData)  
            .map((response: Response) => {  
              return response;                 
            });
}