本文共 2916 字,大约阅读时间需要 9 分钟。
本文翻译自:
Here is my HTML form: 这是我的HTML表单:
I want to upload an image from local machine and want to read the content of the uploaded file. 我想从本地计算机上载图像,并想读取上载文件的内容。 All this I want to do using AngularJS. 我想使用AngularJS进行的所有操作。
When I try to print the value of $scope.file
it comes as undefined. 当我尝试打印$scope.file
的值时,它的值未定义。
参考:
Below is working example of file upload: 以下是文件上传的工作示例:
In this one function called 在这个函数中,
setFiles
From View which will update the file array in controller 从视图将更新控制器中的文件数组
or 要么
You can check jQuery File Upload using AngularJS 您可以使用AngularJS检查jQuery文件上传
works fine in chrome and IE (if you update CSS a little in background-image). 在chrome和IE中工作正常(如果您在背景图片中稍微更新了CSS)。 This is used for updating progress bar: 这用于更新进度条:
scope.progress = Math.round(evt.loaded * 100 / evt.total)
but in FireFox angular's [percent] data is not updated in DOM successfully,although files are uploading successfully. 但是在FireFox中,虽然文件上传成功,但是在DOM中无法成功更新angular的[percent]数据。
Some of the answers here propose using FormData()
, but unfortunately that is a browser object not available in Internet Explorer 9 and below. 这里的一些答案建议使用FormData()
,但是不幸的是,这是Internet Explorer 9及更低版本中不可用的浏览器对象。 If you need to support those older browsers, you will need a backup strategy such as using <iframe>
or Flash. 如果需要支持那些较旧的浏览器,则需要一种备份策略,例如使用<iframe>
或Flash。
There are already many Angular.js modules to perform file uploading. 已经有许多Angular.js模块可以执行文件上传。 These two have explicit support for older browsers: 这两个对较旧的浏览器有明确的支持:
And some other options: 还有其他一些选择:
One of these should fit your project, or may give you some insight into how to code it yourself. 其中之一应适合您的项目,或者可以使您对如何自己编写代码有所了解。
The easiest is to use HTML5 API, namely 最简单的是使用HTML5 API,即
HTML is pretty straightforward: HTML非常简单:
In your controller define 'add' method: 在您的控制器中定义“添加”方法:
$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);}
Browser Compatibility 浏览器兼容性
Desktop Browsers 桌面浏览器
Edge 12, Firefox(Gecko) 3.6(1.9.2), Chrome 7, Opera* 12.02, Safari 6.0.2 Edge 12,Firefox(Gecko)3.6(1.9.2),Chrome 7,Opera * 12.02,Safari 6.0.2
Mobile Browsers 移动浏览器
Firefox(Gecko) 32, Chrome 3, Opera* 11.5, Safari 6.1 Firefox(壁虎)32,Chrome 3,Opera * 11.5,Safari 6.1
Note : readAsBinaryString() method is deprecated and should be used instead. 注意:不建议使用readAsBinaryString()方法,而应使用 。
You can achieve nice file and folder upload using . 您可以使用实现漂亮的文件和文件夹上传。
Check out a demo here 在这里查看演示
It doesn't support IE7, IE8, IE9, so you'll eventually have to use a compatibility layer 它不支持IE7,IE8,IE9,因此您最终必须使用兼容层
转载地址:http://zzjnb.baihongyu.com/