如何在angular2中上传图片?在post方法中

时间:2018-04-10 12:28:23

标签: angular2-routing angular2-forms angular2-services

HTML

    <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>
        <button type="submit" class="btn btn-success  "     (click)="save(productname,sales,files);onChangeroot(root)">Submit</button>

component.ts

 export class NewProductComponent {
   productservice:ProductsService
     selectedFile = null;
     onfileSelected(event){
       console.log(event);
       this.selectedFile =<File>event.target.files[0];
     }

    save1(productname,sales,files)
       {                   
         let obj =  {
                       'pro_name':productname.value,
                        'sales':sales.value,                    
                        'image':files.value                                   
                    }

         var json = JSON.stringify(obj)
         console.log(json)
         const fd = new FormData();
         fd.append('image', this.selectedFile , this.selectedFile.name );
         this.http.post('http://127.0.0.1:8000/product/images/',fd)
         this.service.save_user1(json).subscribe(response => console.log('Inserted Successfully'),
               error => console.log(error));             
             }   
        }

service.ts

  export class ProductsService {
       save_user1(exp_data:any): Observable<any[]>{
       console.log("console",exp_data)
       let headers = new Headers({ 'Content-Type': 'application/json'});
       let options = new RequestOptions({ headers: headers });
       console.log("options",options)
       return this.http.post("http://127.0.0.1:8000/product/", exp_data, options)
                   .map(response => response.json())
                   .catch(error => Observable.throw(error.statusText));
   };  
   }

在控制台事件中选择图像后,在提交表单时工作正常,但该图像除了图像以外,所有其他数据都成功存储在数据库中。

我是以这种方式尝试但是无法发布图片,。所以请帮我怎么做?

1 个答案:

答案 0 :(得分:0)

我认为您的服务方法需要改变。通常我们必须将文件作为多部分表单数据发送。我的工作副本是:

let formData: FormData = new FormData();
    formData.append('file', this.imageFile);
    this.http.post(this.url , formData) .subscribe(
    (result) => {
        console.log(result); 
    },
    (error) => {
        console.error(error);
    }
);