AngularJs 上传文件到服务器

来源:互联网 发布:linux7安装mysql 编辑:程序博客网 时间:2024/04/30 12:23

   现在项目中需要运用到AngularJs,其中用到AngularJs中上传文件功能,借此,记录下,怎样运用AngularJs中的组件。首先,去下载一个叫ng-file-upload的插件。下载地址:https://github.com/danialfarid/ng-file-upload  上面也关于怎样运用这个插件的。该插件需要自己在项目中定义到具体路径

define([

'angular',
'angular-route',
'angular-resource',
'angular-animate',
'angular-growl',
'angular-ngupload',
'controllers/index',
'directives/index',
'filters/index',

'services/index'

然后,代码中<button type="file"
ngf-select="uploadAPFiles($file, $invalidFiles)"
ngf-max-height="1000" ngf-max-size="150MB" ngf-pattern="'.bin'">
选择程序包并上传</button> 

上面代码中,主要是AngularJs中基础运用,通过uploadAPFiles方法,该方法在js文件中定义。

说说几个参数的意思,ngf-max-size表示限制上传的大小,ngf-pattern表示允许上传哪些文件,限制作用。JS文件中定义的方法,具体实现上传代码。下面:

$scope.uploadAPFiles = function(file,
errFiles) {


$scope.errFile = errFiles
&& errFiles[0];
if ($scope.errFile != undefined) {


BootstrapDialog
.show({
title : '通知消息',
message : '请选择合法的文件类型!'
});


}
if (file) {
file.upload = Upload.upload({
url : upload_url,
data : {
file : file
}
});


file.upload
.then(
function(
response) {
console
.log('Success '
+ response.config.data.file.name
+ 'uploaded. Response: '
+ response.data);
BootstrapDialog
.show({
title : '通知消息',
message : '上传AP程序成功'
});
$timeout(function() {
file.result = response.data;
});
},
function(
response) {
if (response.status > 0)
$scope.errorMsg = response.status
+ ': '
+ response.data;
},
function(evt) {
file.progress = Math
.min(
100,
parseInt(100.0
* evt.loaded
/ evt.total));
if (file.progress == 100) {


}
});
}
}

通过上面配置,填写好接口实现,就将文件上传到服务中,可以具体实现正在上传的文件的百分比,这个根据自己的需要去修改就可以了。谢谢!(有问题的地方可以大家交流,qq:1149748612)

0 1