前臺:php
<div ng-controller="UploaderController" > <input type="file" file-model="myFile" > <button ng-click="save()" >保存</button> </div>
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"); }); } });
在GET方法中能夠使用params ,在POST/PUT/PATCH/DELETE中不能使用params 來傳遞數據,要使用data來傳遞。