实际上,我曾经推出过自己的上传器……但只是因为我不喜欢任何已经制作的 JQuery 上传器。不幸的是,这是专有的,我不能在互联网上发布它......但是......我可以向您展示如何使用来自 Angular 的任何 JQuery 插件:
有人可能会说它很容易使用现有的上传器并将其集成到 AngularJS 中 - 我会说:如果它很容易,那么应该有人已经做到了。
假设我有一个 jQuery 插件,它通过选择一个 div 并在其上调用 pluginUploadCall()...
app.directive('myJqueryPluginUploader', function() {
return {
restrict: 'A',
link: function(scope, elem, attr, ctrl) {
// elem is a jQuery lite object
// or a jQuery object if jQuery is present.
// so call whatever plugins you have.
elem.pluginUploadCall();
}
};
});
这就是它的使用方法。
<div my-jquery-plugin-uploader></div>
Angular 实际上与 jQuery 集成得非常好,因此任何在 jQuery 中工作的插件都应该在 Angular 中很容易地工作。当你想让依赖注入保持活跃时,唯一的技巧就出现了,这样你就可以让你的 Angular 应用程序保持可测试性。 JQuery 不太擅长 DI,因此您可能需要跳过一些障碍。
如果你想自己动手,我可以告诉你我做了这样的事情:
app.directive('customUploader', function(){
return {
restrict: 'E',
scope: {},
template: '<div class="custom-uploader-container">Drop Files Here<input type="file" class="custom-uploader-input"/><button ng-click="upload()" ng-disabled="notReady">Upload</button></div>',
controller: function($scope, $customUploaderService) {
$scope.notReady = true;
$scope.upload = function() {
//scope.files is set in the linking function below.
$customUploaderService.beginUpload($scope.files);
};
$customUploaderService.onUploadProgress = function(progress) {
//do something here.
};
$customUploaderService.onComplete = function(result) {
// do something here.
};
},
link: function(scope, elem, attr, ctrl) {
fileInput = elem.find('input[type="file"]');
fileInput.bind('change', function(e) {
scope.notReady = e.target.files.length > 0;
scope.files = [];
for(var i = 0; i < e.target.files.length; i++) {
//set files in the scope
var file = e.target.files[i];
scope.files.push({ name: file.name, type: file.type, size: file.size });
}
});
}
});
其中$customUploaderService 将是您使用Module.factory() 创建的自定义服务,它使用$http 发布文件并检查服务器上的进度。
我知道这很含糊,很抱歉,我只能提供这些,但我希望这会有所帮助。
编辑:拖放文件上传有点 CSS 的技巧,顺便说一句......对于 Chrome 和 FF,你所做的就是把它放在一个包含 div 中......然后做这样的事情:
<div class="uploadContainer">Drop Files Here<input type="file"/></div>
div.uploadContainer {
position: relative;
width: 600px;
height: 100px;
}
div.uploadContainer input[type=file] {
visibility: hidden;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
...现在,您在该 div 上放置的任何内容都将真正在文件上传时被删除,您可以使 div 看起来像您想要的任何东西。