angularjs php 文件上传
项目结构
index.html
<!DOCTYPE html>
<html ng-app="m" ng-cloak>
<head>
<meta charset="UTF-8">
<title>angularjs 文件上传</title>
<script type="text/javascript" src="/assets/js/angular.min.js"></script>
<script type="text/javascript" src="/assets/js/ng-file-upload-shim.min.js"></script>
<script type="text/javascript" src="/assets/js/ng-file-upload.min.js"></script>
<script type="text/javascript" src="/assets/js/index.js"></script>
</head>
<body ng-controller="uploadFileController">
<button ng-change='upfileSubmit()' ngf-select ng-model="file" name="file" ngf-min-height="100" multiple class="common-btn">请选择图片</button>
</body>
</html>
/**
*
*/
var app_main = angular.module("m",["ngFileUpload"]);
app_main.config(function($httpProvider){
$httpProvider.defaults.transformRequest=function(obj){
var str=[];
for(var p in obj){
str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));
}
return str.join("&");
};
$httpProvider.defaults.headers.post={
'Content-Type':'application/x-www-form-urlencoded'
};
});
app_main.controller("uploadFileController",function($rootScope,$scope,$http,Upload){
$scope.file = null;
$scope.upfileSubmit = function(){
angular.forEach($scope.file, function(file, index){
$scope.upload(file, index);
});
};
$scope.upload = function(file,index){
console.log(file);
Upload.upload({
url: '/php/index.php',
file: file
}).progress(function(evt){
console.log(evt);
}).success(function(a){
$scope.file = null;
}).error(function(data, status, headers, config){
$scope.file = null;
})
};
});
<?php
ini_set("display_errors","On");
error_reporting(E_ALL);
$path = dirname(dirname(__FILE__))."/user_information/img/";
$uid = "1";
$files = $_FILES;
if(isset($files["file"])){
$files["shengfengzheng"] = $files["file"];
}
if ($files['shengfengzheng']['type'] != "image/jpeg"){
die(json_encode(array("ret"=>"图片格式错误,请上传.jpg图片","file"=>$files)));
}
if(($files['shengfengzheng']['size']/1000) > 1024){
die(json_encode(array("ret"=>"身份证图片不能大于1M")));
}
if(!file_exists($path.$uid)){
mkdir($path.$uid);
}
$img_name = basename($path.$uid."/".$files['shengfengzheng']['name']);
$extpos = strrpos($img_name,'.');
$ext = substr($img_name,$extpos+1);
move_uploaded_file($files['shengfengzheng']['tmp_name'],$path.$uid."/identity_card.".$ext);
die(json_encode(array("ret"=>"身份证照片上传成功")));