【问题标题】:Angular 2 post request not send image dataAngular 2 post请求不发送图像数据
【发布时间】:2017-04-26 15:46:05
【问题描述】:

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

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: {}} 的内容。为什么它发送一个空数据?

【问题讨论】:

  • 是否可以与 this.file = event.srcElement.files[0] 一起使用?
  • 是的,确实如此,但请求仍然发送一个 void 对象

标签: javascript node.js angular multer


【解决方案1】:

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

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

【讨论】:

  • 非常感谢,我对http请求一无所知!
猜你喜欢
  • 2021-01-13
  • 2013-07-07
  • 2019-09-15
  • 2018-05-26
  • 2015-12-30
  • 2011-05-22
  • 2018-08-04
  • 2017-05-12
  • 1970-01-01
相关资源
最近更新 更多