2017-04-25 49 views
0

我使用表單發送圖像,並在提交時發送沒有數據的請求。在這裏我的代碼:Angular 2發佈請求不發送圖像數據

component.html

<form [formGroup]="logoImageForm" *ngIf="representativeSelected != null" (ngSubmit)="onSubmit(logoImageForm)"> 
    <md-grid-list cols="6" rowHeight="50"> 
     <md-grid-tile> 
      <input type="file" id="logo_image" formControlName="logo_image" name="logo_image" ngModel (change)="onChange($event)"> 
     </md-grid-tile> 
    </md-grid-list> 
    <md-card-actions> 
     <button md-raised-button color="primary" type="submit">Save</button> 
    </md-card-actions> 
</form> 

component.ts

onChange(event){ 
    this.file = event.target.files[0]; 
} 

onSubmit(logoImage){ 
this.representativeS.uploadLogoImage(this.file) 
    .subscribe(
    data => { 
    swal('', 'Image updated!', 'success'); 
    }, 
    error => { 
    swal('Error', '<p>' + error.message + '</p>', 'success'); 
    }); 
} 

代表(服務)

uploadLogoImage(file){ 
    let url = this.routesS.getApiRoute('logoImage'); 
    console.log(file); 
    return this.http.post(url, JSON.stringify({fileData: file}),{ withCredentials: true, headers: this.headersImage }) 
    .map((response: Response) => { 
     return response.json(); 
    }) 
    .catch(this.handleError); 
} 

的NodeJS

var storage = multer.diskStorage({ 
destination: function (req, file, callback) { 
    callback(null, 'path/test'); 
}, 
filename: function (req, file, callback) { 
    callback(null, 'logo-image') 
} 
}); 

var upload = multer({ storage: storage }).single('logo-image'); 

router.route('/representatives/:id/logoImage') 
    .post((req, res, next) => { 
     upload(req, res, function (err) { 
      if (err) { 
       console.log('Error Occured'); 
       return; 
      } 
      res.end('Your File Uploaded'); 
     }) 
    }); 

當我做了提交,如果我檢查我的請求sended它表明類似的東西{fileData: {}}。爲什麼它發送一個無效的數據?

+0

是否與this.file = event.srcElement.files工作[0]? – Powkachu

+0

是的,它確實,但請求仍然發送一個無效對象 – Crisiiii

回答