这次我们用ng-file-upload 控件来实现上传功能
1 下载工具
bower install ng-file-upload
bower install ng-file-upload-shim (for non html5 suppport 支持非html5浏览器)
2写一个页面
<div class="input-group">
<input class="form-control" ng-model="formModel.picture" type="text" style="width: 500px;">
<div class="btn btn-default" ngf-select="upload($file)" ngf-pattern="'image/*'" ngf-multiple="false" ng-model="file" name="file">选择文件</div>
<div style="height:80px">
<img style="height:100%;" ng-src="{{formModel.picture}}">
</div>
</div>
3 angular控制器
controllers.controller('xxx', function ($scope, $window, $http) {
$scope.file={};
$scope.upload = function () {
if (!$scope.file) return;
$scope.isLoadding = true;
var formData = new FormData();
formData.append("file", $scope.file);
$http.post('xxx/image', formData, {
transformRequest: function (data, headersGetterFunction) {
return data;
},
headers: {'Content-Type': undefined}
}).success(function (resultJson, status) {
//校验数据哦
if (resultJson.success) {
$scope.formModel.picture = resultJson.data;
} else {
$scope.tipAlert(resultJson.errorMsg);
}
});
};
});
4 Spring后台
@ResponseBody
@RequestMapping("/image")
public Result<String> imageUpload(@RequestParam(value = "file", required = true) MultipartFile imgFile) {
String picUrl="";
String regex = ".*\\.(jpg|png|bmp|gif)";
if (Pattern.matches(regex, imgFile.getOriginalFilename()) && imgFile.getSize() <= 2 * 1024 * 1024) {
File img = new File("ba_" + convert(imgFile.getOriginalFilename()));
//...
}
return Result.wrapSuccess(picUrl);
}
5 示意图
参考文章
http://www.cnblogs.com/jach/p/5734920.html
https://github.com/danialfarid/ng-file-upload
http://blog.csdn.net/csdnmmcl/article/details/51033954