2016-11-18 40 views
0

我正在基於REST Api創建Web應用程序。我試圖在前端加載文件並將其發送到後端,然後將其保存到我的mongodb數據庫(GridFSDBFile)中。 用FormData發送POST後,從前端(角度)到Spring Boot後端,我收到空對象。映射後多部分FormData空

前端功能:

saveNewImage(userFile, fileName){ 
     var formdata = new FormData(); 
     formdata.append('name', fileName); 
     formdata.append('file', userFile); 
     return this.$http({ 
      url: this.getUrl('file/uploadNew'), 
      method: "POST", 
      data: formdata, 
      cache: false, 
      headers: { 
       "Content-Type": "multipart/*;boundary=gc0p4Jq0M2Yt08jU534c0p" 
      }, 
      processData: false 
     }); 

在後端控制器我要地圖傳入的請求,並保存文件到我的數據庫。我試圖用@ModelAttribute adnotations映射這樣的:

@RequestMapping(value = "/uploadNew", headers = "content-type=multipart/*", method = RequestMethod.POST) 
    @ResponseBody 
    public ResponseEntity<String> uploadFileHandler(@ModelAttribute("name") String name, @ModelAttribute("file") MultipartFile file) { 
     FileInputStream fis = null; 
     ObjectMapper ob = new ObjectMapper(); 
     AnnotationConfigApplicationContext ctx = null; 


//saving file to database 
      (...) 
       return ResponseEntity.status(HttpStatus.OK).body(ob.writeValueAsString("ok")); 
      } catch (JsonProcessingException e) { 
       e.printStackTrace(); 
      } 

      return null; 
     } 

,我得到空字符串名稱和無效的,而不是我的文件,內容如下:

2016-11-18 19:03:03.657 ERROR 14114 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause 

java.lang.NullPointerException: null 

我不知道哪裏出了問題奠定,前端代碼似乎工作正常(網絡調試顯示請求有所需,而不是空字段),它是一個映射問題?如何解決它?

謝謝!

回答

0

萬一有人有同樣的問題,解決方法是內容類型更改爲

headers: {'Content-Type': undefined }