Sending file object to Spring Rest controller through angular 5

后端 未结 2 671
梦如初夏
梦如初夏 2020-12-22 07:02

I am trying to upload a file on client side and send HTTP Post request to Spring Rest Controller. But when I receive the file object in Rest controller I could see it as \'n

2条回答
  •  猫巷女王i
    2020-12-22 07:45

    the easiest thing to do (according to me) is to use a FormData object.

    Here is how :

    @viewChild() fileInput: ElementRef;
    
    onFileChange(event) {
      const files = this.fileInput.nativeElement.files as FileList;
      const file = files.item(0);
    
      const formData = new FormData();
      formData.append('pdf', file, file.name);
      this.http.post('abc', formData, {
        headers: new HttpHeaders().set('content-type','application/pdf')
      }).subscribe(
        data => console.log(data),
        err => console.log(err)
      );
    }
    

    Try this and tell me what you see on Spring side.

提交回复
热议问题