AngularJs實現Multipart/form-data 文件的上傳

由於公司的需要,我們從java後臺傳統的JSP轉向了使用前後臺完全分離的模式來進行開發。後臺完全提供接口,可供網頁PC端和移動app端調取來獲取數據。前臺使用anjularjs來展示數據。

廢話不多說了,直接進入主題吧。

一. 傳統的表單提交文件是這樣的 
前臺:

    <from action="your url" method="post"         enctype="multipart/form-data">
    <input type="file" name="logo">
    <input type="submit" value="提交">
    </from>
  • 1
  • 2
  • 3
  • 4

後臺springmvc的接受:

 @ApiOperation(value = "上傳文件", notes = "上傳文件test", responseClass = "DataVo")
    @RequestMapping(value = "/upload", produces = { "application/json" }, method =RequestMethod.POST )
    public @ResponseBody DataVo upload(
    @ApiParam(value = "logo", required = true) @RequestParam(value = "logo", required = true) MultipartFile logo,HttpServletRequest request){
    //這裏的logo就是接受的文件了
    if(logo!=null){
       //進行操作吧
        System.out.println(logo.getOriginalFilename());
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

二. anjularjs的處理文件上傳 
前臺:

<div  ng-controller="UploaderController" >
    <input type="file" file-model="myFile" >
    <button ng-click="save()" >保存</button>
</div>
  • 1
  • 2
  • 3
  • 4

js文件: 
這裏要注意的是,因爲是通過anjularjs的http請求來上傳文件的,所以要讓當前的request成爲一個Multipart/form-data請求,anjularjs對於post和get請求默認的Content-Type header 是application/json。通過設置‘Content-Type’: undefined,這樣瀏覽器不僅幫我們把Content-Type 設置爲 multipart/form-data,還填充上當前的boundary,如果你手動設置爲: ‘Content-Type’: multipart/form-data,後臺會拋出異常:the current request boundary parameter is null。 
ps: 
通過設置 transformRequest: angular.identity ,anjularjs transformRequest function 將序列化我們的formdata object.

 $scope.save = function() {    
        var fd = new FormData();
        var file = document.querySelector('input[type=file]').files[0];
        fd.append('logo', file); 
         $http({
              method:'POST',
              url:"your url",
              data: fd,
              headers: {'Content-Type':undefined},
              transformRequest: angular.identity 
               })   
              .success( function ( response )
                       {
                       //上傳成功的操作
                       alert("uplaod success");
                       }); 

     }
    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

後臺:同1中的後臺

ps:上面的file的獲取還可以通過:var file = $scope.myFile.同時要注意在js中 data: fd,不能像普通的參數一樣寫爲:params:{ fd,…},具體的解釋是: 
官方文檔

params – {Object.<string|Object>} – Map of strings or objects which will be serialized with theparamSerializer and appended as GET parameters.
data – {string|Object} – Data to be sent as the request message data.
  • 1
  • 2

在GET方法中可以使用params ,在POST/PUT/PATCH/DELETE中不能使用params 來傳遞數據,要使用data來傳遞。

三.小結 
這樣就實現了簡單的anjularjs文件的上傳,自己總結了一下,希望可以幫助到大家,加油!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章