File Upload using AngularJS
这是我的HTML表单:
1 2 3 4 | <form name="myForm" ng-submit=""> <input ng-model='file' type="file"/> <input type="submit" value='Submit'/> </form> |
我想从本地计算机上传一个图像,并想读取上传文件的内容。我想用安古拉杰来做这些。
当我试图打印
这里的一些答案建议使用
已经有许多angular.js模块要执行文件上载。这两个浏览器对旧浏览器有明确的支持:
- https://github.com/leon/angular-upload-使用iframes作为回退
- https://github.com/danialfrid/ng-file-upload-使用fileapi/flash作为回退
以及其他一些选择:
- https://github.com/nergh/angular-file-upload/
- https://github.com/uor/angular-file
- https://github.com/twilson63/ngupload
- https://github.com/uploadcare/angular-uploadcare网站
其中之一应该适合您的项目,或者可以让您了解如何自己编写代码。
最简单的是使用HTML5 API,即
HTML非常简单:
1 2 | <input type="file" id="file" name="file"/> <button ng-click="add()">Add</button> |
在控制器中定义"添加"方法:
1 2 3 4 5 6 7 8 9 10 11 | $scope.add = function() { var f = document.getElementById('file').files[0], r = new FileReader(); r.onloadend = function(e) { var data = e.target.result; //send your binary data via $http or $resource or do anything else with it } r.readAsBinaryString(f); } |
浏览器兼容性
桌面浏览器
Firefox(Gecko) 3.6(1.9.2), Chrome 7, Internet
Explorer* 10, Opera* 12.02, Safari 6.0.2
移动浏览器
Firefox(Gecko) 32,
Chrome 3,
Internet Explorer* 10,
Opera* 11.5,
Safari 6.1
注意:readasBinaryString()方法已被弃用,应改为使用readasArrayBuffer()。
这是2015年的方式,没有第三方图书馆。适用于所有最新的浏览器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | app.directive('myDirective', function (httpPostFactory) { return { restrict: 'A', scope: true, link: function (scope, element, attr) { element.bind('change', function () { var formData = new FormData(); formData.append('file', element[0].files[0]); httpPostFactory('upload_image.php', formData, function (callback) { // recieve image name to use in a ng-src console.log(callback); }); }); } }; }); app.factory('httpPostFactory', function ($http) { return function (file, data, callback) { $http({ url: file, method:"POST", data: data, headers: {'Content-Type': undefined} }).success(function (response) { callback(response); }); }; }); |
HTML:
1 | <input data-my-Directive type="file" name="file"> |
PHP:
1 2 3 4 5 6 7 8 9 10 | if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) { // uploads image in the folder images $temp = explode(".", $_FILES["file"]["name"]); $newfilename = substr(md5(time()), 0, 10) . '.' . end($temp); move_uploaded_file($_FILES['file']['tmp_name'], 'images/' . $newfilename); // give callback to your angular code with the image src name echo json_encode($newfilename); } |
JS小提琴(仅前端)https://jsfiddle.net/vince123/8d18tsey/31/
以下是文件上传的工作示例:
http://jsfidle.net/vishalvasani/4hqvuu/
在这个函数中
1 | setFiles |
从视图更新控制器中的文件数组
或
您可以使用angularjs检查jquery文件上传
http://blueimp.github.io/jquery-file-upload/angularjs.html
您可以使用Flow.js实现良好的文件和文件夹上传。
https://github.com/flowjs/ng-flow(流量)
在这里观看演示
http://flowjs.github.io/ng-flow/
它不支持IE7、IE8、IE9,因此最终必须使用兼容层
https://github.com/flow js/fusty-flow.js网站
我尝试了@anoyz(正确答案)给出的所有备选方案…最好的解决方案是https://github.com/daniafarid/angular-file-upload
一些特点:
- 进展
- 多文件
- 领域
- 旧浏览器(IE8-9)
这对我来说很好。你只需要注意指示。
在服务器端,我使用nodejs、express 4和multer中间件来管理多部分请求。
使用
因此,当用户选择一个文件时,您可以引用它,而无需用户单击"添加"或"上载"按钮。
1 2 3 | $scope.fileSelected = function (element) { var myFileSelected = element.files[0]; }; |
HTML
1 2 3 4 5 6 7 8 9 10 11 12 | <html> <head></head> <body ng-app ="myApp"> <form ng-controller ="myCtrl"> <input type ="file" file-model="files" multiple/> <button ng-click ="uploadFile()">upload me</button> <li ng-repeat="file in files">{{file.name}} </li> </form> |
脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> angular.module('myApp', []).directive('fileModel', ['$parse', function ($parse) { return { restrict: 'A', link: function(scope, element, attrs) { element.bind('change', function(){ $parse(attrs.fileModel).assign(scope,element[0].files) scope.$apply(); }); } }; }]).controller('myCtrl', ['$scope', '$http', function($scope, $http){ $scope.uploadFile=function(){ var fd=new FormData(); console.log($scope.files); angular.forEach($scope.files,function(file){ fd.append('file',file); }); $http.post('http://localhost:1337/mediaobject/upload',fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }).success(function(d) { console.log(d); }) } }]); |
默认情况下,
1 2 3 4 5 6 7 8 9 10 11 12 13 | angular.module("app",[]); angular.module("app").directive("selectNgFiles", function() { return { require:"ngModel", link: function postLink(scope,elem,attrs,ngModel) { elem.on("change", function(e) { var files = elem[0].files; ngModel.$setViewValue(files); }) } } }); |
1 2 3 4 5 6 7 8 9 10 11 | <script src="//unpkg.com/angular/angular.js"> <body ng-app="app"> AngularJS Input `type=file` Demo <input type="file" select-ng-files ng-model="fileList" multiple> Files {{file.name}} </body> |
1 2 3 4 5 6 7 8 9 | $scope.upload = function(url, fileList) { var config = { headers: { 'Content-Type': undefined }, transformResponse: angular.identity }; var promises = fileList.map(function(file) { return $http.post(url, file, config); }); return $q.all(promises); }; |
使用文件对象发送日志时,设置
简单的指令
Html:
1 | <input type="file" file-upload multiple/> |
JS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | app.directive('fileUpload', function () { return { scope: true, //create a new scope link: function (scope, el, attrs) { el.bind('change', function (event) { var files = event.target.files; //iterate files since 'multiple' may be specified on the element for (var i = 0;i<files.length;i++) { //emit event upward scope.$emit("fileSelected", { file: files[i] }); } }); } }; |
在该指令中,我们确保创建了一个新的作用域,然后监听对文件输入元素所做的更改。当检测到更改时,向所有祖先作用域(向上)发出一个事件,文件对象作为参数。
在控制器中:
1 2 3 4 5 6 7 8 9 | $scope.files = []; //listen for the file selected event $scope.$on("fileSelected", function (event, args) { $scope.$apply(function () { //add the file object to the scope's files collection $scope.files.push(args.file); }); }); |
然后在Ajax调用中:
1 | data: { model: $scope.model, files: $scope.files } |
http://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/
我认为这是角度文件上传:
文件上传用于上载文件的轻量级Angular JS指令。
这是演示页面。功能
- 支持上载进度、正在进行时取消/中止上载、文件拖放(HTML5)、目录拖放(WebKit)、CORS、Put(HTML5)/Post方法、文件类型和大小验证、显示所选图像/音频/视频的预览。
- 使用flash polyfill fileapi进行跨浏览器文件上传和文件阅读器(html5和非html5)。允许在上载文件之前进行客户端验证/修改
- 直接上传到数据库服务couchdb、imgur等…使用upload.http()使用文件的内容类型。这将启用角度HTTP POST/PUT请求的进度事件。
- 单独的填充文件,fileapi文件是按需加载的非html5代码,这意味着如果您只需要html5支持,就没有额外的加载/代码。
- 轻量级使用常规的$http进行上传(非HTML5浏览器使用垫片),因此所有角度$http功能都可用。
https://github.com/danialfrid/ng-file-upload
您的文件和JSON数据同时上传。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | // FIRST SOLUTION var _post = function (file, jsonData) { $http({ url: your url, method:"POST", headers: { 'Content-Type': undefined }, transformRequest: function (data) { var formData = new FormData(); formData.append("model", angular.toJson(data.model)); formData.append("file", data.files); return formData; }, data: { model: jsonData, files: file } }).then(function (response) { ; }); } // END OF FIRST SOLUTION // SECOND SOLUTION // ?f you can add plural file and ?f above code give an error. // You can try following code var _post = function (file, jsonData) { $http({ url: your url, method:"POST", headers: { 'Content-Type': undefined }, transformRequest: function (data) { var formData = new FormData(); formData.append("model", angular.toJson(data.model)); for (var i = 0; i < data.files.length; i++) { // add each file to // the form data and iteratively name them formData.append("file" + i, data.files[i]); } return formData; }, data: { model: jsonData, files: file } }).then(function (response) { ; }); } // END OF SECOND SOLUTION |
您可以使用安全快速的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // Store the file object when input field is changed $scope.contentChanged = function(event){ if (!event.files.length) return null; $scope.content = new FormData(); $scope.content.append('fileUpload', event.files[0]); $scope.$apply(); } // Upload the file over HTTP $scope.upload = function(){ $http({ method: 'POST', url: '/remote/url', headers: {'Content-Type': undefined }, data: $scope.content, }).success(function(response) { // Uploading complete console.log('Request finished', response); }); } |
http://jsfiddle.net/vishalvasani/4hqvu/在Chrome和IE中运行良好(如果您在背景图像中稍微更新css)。用于更新进度条:
1 | scope.progress = Math.round(evt.loaded * 100 / evt.total) |
但在火狐Angular的[percent]中,数据在DOM中没有成功更新,尽管文件上传成功。
HTML
1 | <input type="file" id="file" name='file' onchange="angular.element(this).scope().profileimage(this)" /> |
将"profileImage()"方法添加到控制器
1 2 3 4 5 6 7 8 9 10 11 | $scope.profileimage = function(selectimage) { console.log(selectimage.files[0]); var selectfile=selectimage.files[0]; r = new FileReader(); r.onloadend = function (e) { debugger; var data = e.target.result; } r.readAsBinaryString(selectfile); } |
我知道这是一个延迟条目,但我创建了一个简单的上传指令。你很快就可以开始工作了!
1 | <input type="file" multiple ng-simple-upload web-api-url="/api/Upload" callback-fn="myCallback" /> |
ng simple在GitHub上上载更多,并提供使用Web API的示例。
您可以考虑将IAAS用于文件上载,例如UploadCare。它有一个角度包:https://github.com/uploadcare/angular-uploadcare
从技术上讲,它是作为一个指令来实现的,为上传提供了不同的选项,并为小部件中上传的图像提供了不同的操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <uploadcare-widget ng-model="object.image.info.uuid" data-public-key="YOURKEYHERE" data-locale="en" data-tabs="file url" data-images-only="true" data-path-value="true" data-preview-step="true" data-clearable="true" data-multiple="false" data-crop="400:200" on-upload-complete="onUCUploadComplete(info)" on-widget-ready="onUCWidgetReady(widget)" value="{{ object.image.info.cdnUrl }}" /> |
要使用的更多配置选项:https://uploadcare.com/widget/configure/
这应该是对@jquery guru答案的更新/评论,但由于我没有足够的代表,它将在此处显示。它修复了现在由代码生成的错误。
https://jsfiddle.net/vzhrjotw/
变化基本上是:
1 2 | FileUploadCtrl.$inject = ['$scope'] function FileUploadCtrl(scope) { |
到:
1 2 | app.controller('FileUploadCtrl', function($scope) { |
如果需要,可以自由移动到更合适的位置。
我已经阅读了所有的线程,HTML5API解决方案看起来是最好的。但是它改变了我的二进制文件,以我没有调查过的方式破坏了它们。最适合我的解决方案是:
HTML:
1 2 3 4 | <input type="file" id="msds" ng-model="msds" name="msds"/> <button ng-click="msds_update()"> Upload </button> |
JS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | msds_update = function() { var f = document.getElementById('msds').files[0], r = new FileReader(); r.onloadend = function(e) { var data = e.target.result; console.log(data); var fd = new FormData(); fd.append('file', data); fd.append('file_name', f.name); $http.post('server_handler.php', fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }) .success(function(){ console.log('success'); }) .error(function(){ console.log('error'); }); }; r.readAsDataURL(f); } |
服务器端(php):
1 2 3 4 | $file_content = $_POST['file']; $file_content = substr($file_content, strlen('data:text/plain;base64,')); $file_content = base64_decode($file_content); |
我可以使用以下代码使用AngularJS上传文件:
根据您的问题,需要传递函数
这里的重点是使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | function getFileBuffer(file) { var deferred = new $q.defer(); var reader = new FileReader(); reader.onloadend = function (e) { deferred.resolve(e.target.result); } reader.onerror = function (e) { deferred.reject(e.target.error); } reader.readAsArrayBuffer(file); return deferred.promise; } function ngUploadFileUpload(endPointUrl, file) { var deferred = new $q.defer(); getFileBuffer(file).then(function (arrayBuffer) { $http({ method: 'POST', url: endPointUrl, headers: { "accept":"application/json;odata=verbose", 'X-RequestDigest': spContext.securityValidation, "content-length": arrayBuffer.byteLength }, data: arrayBuffer, transformRequest: [] }).then(function (data) { deferred.resolve(data); }, function (error) { deferred.reject(error); console.error("Error", error) }); }, function (error) { console.error("Error", error) }); return deferred.promise; } |
这作品
文件HTML
1 2 3 4 5 6 7 8 9 10 11 12 | <html> <head> <script src ="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </head> <body ng-app ="app"> <input type ="file" file-model ="myFile"/> <button ng-click ="uploadFile()">upload me</button> </body> <script src="controller.js"> </html> |
控制器JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | var app = angular.module('app', []); app.service('fileUpload', ['$http', function ($http) { this.uploadFileToUrl = function(file, uploadUrl){ var fd = new FormData(); fd.append('file', file); $http.post(uploadUrl, fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }).success(function(res){ console.log(res); }).error(function(error){ console.log(error); }); } }]); app.controller('fileCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){ $scope.uploadFile = function(){ var file = $scope.myFile; console.log('file is ' ); console.dir(file); var uploadUrl ="/fileUpload.php"; // upload url stands for api endpoint to handle upload to directory fileUpload.uploadFileToUrl(file, uploadUrl); }; }]); |
文件管理程序
1 2 3 4 5 | <?php $ext = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION); $image = time().'.'.$ext; move_uploaded_file($_FILES["file"]["tmp_name"],__DIR__. ' \'.$image); ?> |
代码将有助于插入文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <body ng-app ="myApp"> <form ng-controller="insert_Ctrl" method="post" action="" name="myForm" enctype="multipart/form-data" novalidate> <p> <input type="file" ng-model="myFile" class="form-control" onchange="angular.element(this).scope().uploadedFile(this)"> <span style="color:red" ng-show="(myForm.myFile.$error.required&&myForm.myFile.$touched)">Select Picture</span> </p> <input type="button" name="submit" ng-click="uploadFile()" class="btn-primary" ng-disabled="myForm.myFile.$invalid" value="insert"> </form> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"> <script src="insert.js"> </body> |
JS插件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | var app = angular.module('myApp',[]); app.service('uploadFile', ['$http','$window', function ($http,$window) { this.uploadFiletoServer = function(file,uploadUrl){ var fd = new FormData(); fd.append('file', file); $http.post(uploadUrl, fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }) .success(function(data){ alert("insert successfull"); $window.location.href = ' ';//your window location }) .error(function(){ alert("Error"); }); } }]); app.controller('insert_Ctrl', ['$scope', 'uploadFile', function($scope, uploadFile){ $scope.uploadFile = function() { $scope.myFile = $scope.files[0]; var file = $scope.myFile; var url ="save_data.php"; uploadFile.uploadFiletoServer(file,url); }; $scope.uploadedFile = function(element) { var reader = new FileReader(); reader.onload = function(event) { $scope.$apply(function($scope) { $scope.files = element.files; $scope.src = event.target.result }); } reader.readAsDataURL(element.files[0]); } }]); |
SaveYDATA PHP
1 2 3 4 5 6 7 8 | <?php require"dbconnection.php"; $ext = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION); $image = time().'.'.$ext; move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$image); $query="insert into test_table values ('null','$image')"; mysqli_query($con,$query); ?> |
使用简单指令(ng文件模型)的工作示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | .directive("ngFileModel", [function () { return { $scope: { ngFileModel:"=" }, link: function ($scope:any, element, attributes) { element.bind("change", function (changeEvent:any) { var reader = new FileReader(); reader.onload = function (loadEvent) { $scope.$apply(function () { $scope.ngFileModel = { lastModified: changeEvent.target.files[0].lastModified, lastModifiedDate: changeEvent.target.files[0].lastModifiedDate, name: changeEvent.target.files[0].name, size: changeEvent.target.files[0].size, type: changeEvent.target.files[0].type, data: changeEvent.target.files[0] }; }); } reader.readAsDataURL(changeEvent.target.files[0]); }); } } }]) |
并使用
1 2 3 | var formData = new FormData(); formData.append("document", $scope.ngFileModel.data) formData.append("user_id", $scope.userId) |
所有学分归https://github.com/mistralworks/ng-文件-模型
我遇到了一个小问题,您可以在这里查看:https://github.com/mistralworks/ng-file-model/issues/7
最后,这里是一个分叉的回购:https://github.com/okasha93/ng-file-model/blob/patch-1/ng-file-model.js
我们使用了HTML、CSS和AngularJS。下面的示例演示如何使用angularjs上载文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | <html> <head> <script src ="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </head> <body ng-app ="myApp"> <input type ="file" file-model ="myFile"/> <button ng-click ="uploadFile()">upload me</button> var myApp = angular.module('myApp', []); myApp.directive('fileModel', ['$parse', function ($parse) { return { restrict: 'A', link: function(scope, element, attrs) { var model = $parse(attrs.fileModel); var modelSetter = model.assign; element.bind('change', function(){ scope.$apply(function(){ modelSetter(scope, element[0].files[0]); }); }); } }; }]); myApp.service('fileUpload', ['$http', function ($http) { this.uploadFileToUrl = function(file, uploadUrl){ var fd = new FormData(); fd.append('file', file); $http.post(uploadUrl, fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }) .success(function(){ }) .error(function(){ }); } }]); myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){ $scope.uploadFile = function(){ var file = $scope.myFile; console.log('file is ' ); console.dir(file); var uploadUrl ="/fileUpload"; fileUpload.uploadFileToUrl(file, uploadUrl); }; }]); </body> </html> |
以上接受的答案与浏览器不兼容。如果有人存在兼容性问题,请尝试此操作。
小提琴
查看代码
1 2 3 4 5 6 | <input type="file" id="file" name="file"/> <button ng-click="add()">Add</button> <p> {{data}} </p> |
控制器代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | var myApp = angular.module('myApp',[]); function MyCtrl($scope) { $scope.data = 'none'; $scope.add = function(){ var f = document.getElementById('file').files[0], r = new FileReader(); r.onloadend = function(e){ var binary =""; var bytes = new Uint8Array(e.target.result); var length = bytes.byteLength; for (var i = 0; i < length; i++) { binary += String.fromCharCode(bytes[i]); } $scope.data = (binary).toString(); alert($scope.data); } r.readAsArrayBuffer(f); } } |
1 2 3 4 | <form id="csv_file_form" ng-submit="submit_import_csv()" method="POST" enctype="multipart/form-data"> <input ng-model='file' type="file"/> <input type="submit" value='Submit'/> </form> |
在AngularJS控制器中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | $scope.submit_import_csv = function(){ var formData = new FormData(document.getElementById("csv_file_form")); console.log(formData); $.ajax({ url:"import", type: 'POST', data: formData, mimeType:"multipart/form-data", contentType: false, cache: false, processData:false, success: function(result, textStatus, jqXHR) { console.log(result); } }); return false; } |
用简单的话
在HTML中-仅添加以下代码
1 2 3 4 5 | <form name="upload" class="form" data-ng-submit="addFile()"> <input type="file" name="file" multiple onchange="angular.element(this).scope().uploadedFile(this)" /> <button type="submit">Upload </button> </form> |
在控制器中-单击"上载文件按钮"时调用此函数。它将上传文件。你可以控制它。
1 2 3 4 5 | $scope.uploadedFile = function(element) { $scope.$apply(function($scope) { $scope.files = element.files; }); } |
在控制器中添加更多-下面的代码添加到函数中。当您单击按钮时调用此函数,该按钮用于"点击api(post)"。它将把文件(上传的)和表单数据发送到后端。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | var url = httpURL +"/reporttojson" var files=$scope.files; for ( var i = 0; i < files.length; i++) { var fd = new FormData(); angular.forEach(files,function(file){ fd.append('file',file); }); var data ={ msg : message, sub : sub, sendMail: sendMail, selectUsersAcknowledge:false }; fd.append("data", JSON.stringify(data)); $http.post(url, fd, { withCredentials : false, headers : { 'Content-Type' : undefined }, transformRequest : angular.identity }).success(function(data) { toastr.success("Notification sent successfully","",{timeOut: 2000}); $scope.removereport() $timeout(function() { location.reload(); }, 1000); }).error(function(data) { toastr.success("Error in Sending Notification","",{timeOut: 2000}); $scope.removereport() }); } |
在这种情况下……我添加了以下代码作为表单数据
1 2 3 4 5 6 | var data ={ msg : message, sub : sub, sendMail: sendMail, selectUsersAcknowledge:false }; |
上传文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <input type="file" name="resume" onchange="angular.element(this).scope().uploadResume()" ng-model="fileupload" id="resume" /> $scope.uploadResume = function () { var f = document.getElementById('resume').files[0]; $scope.selectedResumeName = f.name; $scope.selectedResumeType = f.type; r = new FileReader(); r.onloadend = function (e) { $scope.data = e.target.result; } r.readAsDataURL(f); }; |
下载文件:
1 2 3 4 5 6 7 8 9 | download resume var app = angular.module("myApp", []); app.config(['$compileProvider', function ($compileProvider) { $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|local|data|chrome-extension):/); $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|local|data|chrome-extension):/); }]); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | app.directive('ngUpload', function () { return { restrict: 'A', link: function (scope, element, attrs) { var options = {}; options.enableControls = attrs['uploadOptionsEnableControls']; // get scope function to execute on successful form upload if (attrs['ngUpload']) { element.attr("target","upload_iframe"); element.attr("method","post"); // Append a timestamp field to the url to prevent browser caching results element.attr("action", element.attr("action") +"?_t=" + new Date().getTime()); element.attr("enctype","multipart/form-data"); element.attr("encoding","multipart/form-data"); // Retrieve the callback function var fn = attrs['ngUpload'].split('(')[0]; var callbackFn = scope.$eval(fn); if (callbackFn == null || callbackFn == undefined || !angular.isFunction(callbackFn)) { var message ="The expression on the ngUpload directive does not point to a valid function."; // console.error(message); throw message +" "; } // Helper function to create new i frame for each form submission var addNewDisposableIframe = function (submitControl) { // create a new iframe var iframe = $("<iframe id='upload_iframe' name='upload_iframe' border='0' width='0' height='0' style='width: 0px; height: 0px; border: none; display: none' />"); // attach function to load event of the iframe iframe.bind('load', function () { // get content - requires jQuery var content = iframe.contents().find('body').text(); // execute the upload response function in the active scope scope.$apply(function () { callbackFn(content, content !=="" /* upload completed */); }); // remove iframe if (content !="") // Fixes a bug in Google Chrome that dispose the iframe before content is ready. setTimeout(function () { iframe.remove(); }, 250); submitControl.attr('disabled', null); submitControl.attr('title', 'Click to start upload.'); }); // add the new iframe to application element.parent().append(iframe); }; // 1) get the upload submit control(s) on the form (submitters must be decorated with the 'ng-upload-submit' class) // 2) attach a handler to the controls' click event $('.upload-submit', element).click( function () { addNewDisposableIframe($(this) /* pass the submit control */); scope.$apply(function () { callbackFn("Please wait...", false /* upload not completed */); }); var enabled = true; if (options.enableControls === null || options.enableControls === undefined || options.enableControls.length >= 0) { // disable the submit control on click $(this).attr('disabled', 'disabled'); enabled = false; } $(this).attr('title', (enabled ? '[ENABLED]: ' : '[DISABLED]: ') + 'Uploading, please wait...'); // submit the form $(element).submit(); } ).attr('title', 'Click to start upload.'); } else alert("No callback function found on the ngUpload directive."); } }; }); <form class="form form-inline" name="uploadForm" id="uploadForm" ng-upload="uploadForm12" action="rest/uploadHelpFile" method="post" enctype="multipart/form-data" style="margin-top: 3px;margin-left: 6px"> <button type="submit" id="mbUploadBtn" class="upload-submit" ng-hide="true"></button> </form> @RequestMapping(value ="/uploadHelpFile", method = RequestMethod.POST) public @ResponseBody String uploadHelpFile(@RequestParam(value ="file") CommonsMultipartFile[] file,@RequestParam(value ="fileName") String fileName,@RequestParam(value ="helpFileType") String helpFileType,@RequestParam(value ="helpFileName") String helpFileName) { } |