Angular 2 post请求不发送图像数据

时间:2017-04-25 11:51:31

标签: javascript node.js angular multer

我正在使用表单发送图像,当提交时,发送没有数据的请求。这是我的代码:

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');
       })
   });   

当我进行提交时,如果我检查了我的请求,则会显示类似{fileData: {}}的内容。为什么发送无效数据?

1 个答案:

答案 0 :(得分:1)

我认为问题在于您如何发送文件。

另一个问题的答案可能会对您有所帮助:https://stackoverflow.com/a/35669598/5049472