AngularJS文件上传

前台: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来传递。
相关文章
相关标签/搜索