html:javascript
<script type="text/javascript" src="js/angular-file-upload.min.js"></script>html
<img id="photo" src="" style="height: 60px; width: 60px;">
<span class="span3" data-type="logo" ng-click="uploadFile($event.target)">選擇相片</span>
<span class="tips1">注:照片大小均限制爲5M之內</span>
<input type="file" style="display: none" id="file" accept="image/*" onchange="fileChange();" ng-file-select="onFileSelect($files)">
<input type="file" style="display: none" id="file1" accept="image/*" ng-file-select="onFileSelect($files)">java
js:app
angular.module("app", ['angularFileUpload'])dom
.controller("upload", function($scope, $http,$location,$upload){post
var limitSize = 5 * 1024 * 1024;url
$scope.onFileSelect = function ($files) {spa
for(var i = 0; i < $files.length; i++){
$scope.file = $files[i];htm
if($scope.file.size <= limitSize){
$scope.upload = $upload.upload({
url: con.host+"upload", //con.host (是你的請求後臺方法路徑「upload」 是你的方法)
file: $scope.file
}).success(function (data) {
if(data.status != 'success'){
alert("上傳失敗");
}else{圖片
var map = {};
map[$scope.type] = data.path;
$scope.postParams.pt_image = data.path;
var file = document.getElementById("file").files[0];
$("#photo").attr("src", window.URL.createObjectURL(file));
}
});
}else{
alert("圖片大小不得超過5M");
}
}
}
$scope.uploadFile = function(target){
$scope.type = $(target).attr("data-type");
if($scope.type == 'logo'){
$("#file").click();
}else{
$("#file1").click();
}
}
function fileChange(){
alert("file");
var file = document.getElementById("file").files[0];
$("#photo").attr("src", window.URL.createObjectURL(file));
}
});
java:
@RequestMapping(value="/upload",method=RequestMethod.POST)
public void doAction(MultipartHttpServletRequest req, HttpServletResponse res) {
JSONObject obj = new JSONObject();
MultipartFile file = req.getFile("file");
System.out.println(file+"=file");
PrintWriter out = null;
try {
out = res.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
out.print(saveFilePic(file,req));
}
private JSONObject saveFilePic(MultipartFile file,MultipartHttpServletRequest req) { JSONObject obj = new JSONObject(); if(file == null) { obj.put("status", "fail"); obj.put("reason", "file is null"); return obj; } String fileName = file.getOriginalFilename(); // 獲取圖片的擴展名 String extensionName = fileName .substring(fileName.lastIndexOf(".") + 1); //擴展名判斷是否爲圖片 if(!FileUtils.picExtCheck(extensionName)) { obj.put("status", "fail"); obj.put("reason", "file is null"); return obj; } String filePath = req.getSession().getServletContext().getRealPath("/") + "upload/" //這裏是項目獲取路徑 + FileUtils.getRandomFileName()+"."+extensionName; //這裏是隨機獲取文件名 加文件後綴名 File path = new File(filePath); try {//create path if(!path.exists()) { path.mkdirs(); } file.transferTo(path); } catch(Exception e) { e.printStackTrace(); } obj.put("status", "success"); String paths = path.toString(); System.out.println(paths+"---------------"); obj.put("path", paths.split("secxpen")[1].replace("/", "\\")); return obj; }