AngularJs實(shí)現(xiàn)Multipart/form-data 文件的上傳
由于公司的需要,我們從Java后臺傳統(tǒng)的JSP轉(zhuǎn)向了使用前后臺完全分離的模式來進(jìn)行開發(fā)。后臺完全提供接口,可供網(wǎng)頁P(yáng)C端和移動app端調(diào)取來獲取數(shù)據(jù)。前臺使用anjularjs來展示數(shù)據(jù)。
廢話不多說了,直接進(jìn)入主題吧。
一. 傳統(tǒng)的表單提交文件是這樣的
前臺:
<from action="your url" method="post" enctype="multipart/form-data">
<input type="file" name="logo">
<input type="submit" value="提交">
</from>
后臺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){
//進(jìn)行操作吧
System.out.println(logo.getOriginalFilename());
}
}
二. anjularjs的處理文件上傳
前臺:
<div ng-controller="UploaderController" >
<input type="file" file-model="myFile" >
<button ng-click="save()" >保存</button>
</div>
js文件:
這里要注意的是,因為是通過anjularjs的http請求來上傳文件的,所以要讓當(dāng)前的request成為一個Multipart/form-data請求,anjularjs對于post和get請求默認(rèn)的Content-Type header 是application/json。通過設(shè)置‘Content-Type’: undefined,這樣瀏覽器不僅幫我們把Content-Type 設(shè)置為 multipart/form-data,還填充上當(dāng)前的boundary,如果你手動設(shè)置為: ‘Content-Type’: multipart/form-data,后臺會拋出異常:the current request boundary parameter is null。
ps:
通過設(shè)置 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
- 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,不能像普通的參數(shù)一樣寫為: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.
在GET方法中可以使用params ,在POST/PUT/PATCH/DELETE中不能使用params 來傳遞數(shù)據(jù),要使用data來傳遞。
三.小結(jié)
這樣就實(shí)現(xiàn)了簡單的anjularjs文件的上傳,自己總結(jié)了一下,希望可以幫助到大家,加油!
|