2017-07-19 30 views
0

我想從Angular2上傳配置文件圖像,而後端是在Spring Boot Rest API中支持多部分數據。我沒有收到後臺請求,並與400使用Spring引導從Angular 2上傳文件時出錯Rest API

碼錯誤鉻回報下面給出:

前端:

HTML:

<input class="file" type="file" (change)="uploadProfileImgOnChange($event)"> 

TS:

uploadProfileImgOnChange(event: any) { 
     let fileList: FileList = event.target.files; 
     if (fileList.length > 0) { 
      this.file = fileList[0]; 

      this.requestsService.postRequestMultipartFormData(
       '/admin/uploadProfileImg/' + this.id 
       , this.file) 
       .subscribe(
        (response: Response) => { 
         if (response['responseCode'] === 'ADM_SUC_08') { 
          console.log(); 
         } 
        }, 
        (error: any) => { 
         this.apUtilServer.tokenExpired(error.json()['error']); 
         //console.log(error.json()) 
        } 
       ); 
} 
} 

postRequestMultipartFormData(url: any, data: any) { 
     data = this.removeUndefined(data); 
     var formData = new FormData(); 
     const headers = new Headers(); 
     formData.append('file', data, data.name); 
     if (this.getToken()) { 
      headers.append('Authorization', 'Bearer ' + this.getToken()); 
     } 
     headers.append('Accept', 'application/json'); 
     console.log(headers); 
     return this.http.post('http://127.0.0.1:8080/AdminPortal/admin/' + url, formData, {headers: headers}) 
      .map((response: Response) => { 
       return response.json(); 
      }) 
    } 

後端:

@RequestMapping(value = "/uploadProfileImg/{id}", method = RequestMethod.POST) 
    public ResponseEntity<?> uploadProfileImage(HttpServletRequest request, 
               @PathVariable("id") long id, 
               @RequestParam("file") MultipartFile file) { 
     logger.info("Update Admin API called {" + id); 

在此先感謝。

URL中沒有問題,所以請忽略做childesh評論。

回答

0

我有問題與Angular4上傳文件到Spring Boot。我在這裏找到了解決我的問題的帖子。

以下是原帖:https://stackoverflow.com/a/35669598/1474815

這裏是我用來張貼文件的代碼。它像一個魅力。

uploadFile(file:File):Promise<MyEntity> { 
    return new Promise((resolve, reject) => { 

     let xhr:XMLHttpRequest = new XMLHttpRequest(); 
     xhr.onreadystatechange =() => { 
      if (xhr.readyState === 4) { 
       if (xhr.status === 200) { 
        resolve(<MyEntity>JSON.parse(xhr.response)); 
       } else { 
        reject(xhr.response); 
       } 
      } 
     }; 

     xhr.open('POST', this.getServiceUrl(), true); 

     let formData = new FormData(); 
     formData.append("file", file, file.name); 
     xhr.send(formData); 
    }); 
}