【AngularJS】上传图片

这次我们用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 示意图

[img]http://dl2.iteye.com/upload/attachment/0122/6409/5083973c-5493-36fe-9db6-9e3730ced375.jpeg[/img]


参考文章
http://www.cnblogs.com/jach/p/5734920.html
https://github.com/danialfarid/ng-file-upload
http://blog.youkuaiyun.com/csdnmmcl/article/details/51033954
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值