【问题标题】:How to upload image post method in angular 2?如何在 Angular 2 中上传图片发布方法?
【发布时间】:2018-09-27 09:11:09
【问题描述】:

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。我不知道如何上传图片。

【问题讨论】:

  • 可以使用表单数据上传angular 2中的文件。
  • “这是我目前尝试过的”,什么不起作用?

标签: angular angular2-template angular2-forms


【解决方案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;                 
            });
}

【讨论】:

  • 感谢您的回复。我已经创建了服务层。实际上我是 Angular2 的新手,所以你能告诉我在哪里添加这个。
  • 是的,当然.. 将此方法添加到您的产品服务中。并从 createNewProduct 方法调用此方法。
  • 实际上,我对要发送产品名称和销售等数据的图像有疑问。
  • 您可以将字段附加到 formData 对象。我会更新答案。
  • 我已经尝试过了,但我怀疑我已经在服务层中使用了 save_user。我所做的是我删除了我的服务层并粘贴了你给出的内容,但它显示了 500 个内部错误。
猜你喜欢
  • 2017-11-15
  • 2017-09-13
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
  • 2017-01-23
  • 2013-01-17
  • 2020-08-12
  • 1970-01-01
相关资源
最近更新 更多