angularjs與springmvc文件上傳

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


https://blog.csdn.net/wei389083222/article/details/51289704
java


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

因爲公司的須要,咱們從java後臺傳統的JSP轉向了使用先後臺徹底分離的模式來進行開發。後臺徹底提供接口,可供網頁PC端和移動app端調取來獲取數據。前臺使用anjularjs來展現數據。spring

廢話很少說了,直接進入主題吧。json

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

<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的接受:mvc

@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的處理文件上傳 
前臺:app

<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.ide

$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中的後臺post

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

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文件的上傳,本身總結了一下,但願能夠幫助到你們,加油!

相關文章
相關標籤/搜索