angular-file-upload
Lightweight Angular JS directive to upload files.
Here is the DEMO page.
To help development of this module give it a thumbs up at ngmodules or get me a cup of tea .
Migration notes: version 3.0.0 version 3.1.0 version 3.2.0 version 4.0.0
Table of Content:
## Features
- Supports upload progress, cancel/abort upload while in progress, File drag and drop (html5), Directory drag and drop (webkit), CORS,
PUT(html5)
/POST
methods, validation of file type and size. - Cross browser file upload (
HTML5
and non-HTML5
) with Flash polyfill FileAPI. Allows client side validation/modification before uploading the file - Direct upload to db services CouchDB, imgur, etc... with file's content type using
$upload.http()
. This enables progress event for angular http POST
/PUT
requests. - Seperate shim file, FileAPI files are loaded on demand for
non-HTML5
code meaning no extra load/code if you just need HTML5 support. - Lightweight using regular
$http
to upload (with shim for non-HTML5 browsers) so all angular $http
features are available
## Usage
###Sample:
jsfiddle http://jsfiddle.net/nmdcwf3w/
<script src="angular.min.js"></script>
<script src="ng-file-upload-shim.min.js"></script>
<script src="ng-file-upload.min.js"></script>
<div ng-app="fileUpload" ng-controller="MyCtrl">
watching model:
<div class="button" ngf-select ng-model="files">Upload using model $watch</div>
<div class="button" ngf-select ngf-change="upload($files)">Upload on file change</div>
Drop File:
<div ngf-drop ng-model="files" class="drop-box"
ngf-drag-over-class="dragover" ngf-multiple="true" ngf-allow-dir="true"
ngf-accept="'.jpg,.png,.pdf'">Drop Images or PDFs files here</div>
<div ngf-no-file-drop>File Drag/Drop is not supported for this browser</div>
</div>
JS:
var app = angular.module('fileUpload', ['angularFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', function ($scope, Upload) {
$scope.$watch('files', function () {
$scope.upload($scope.files);
});
$scope.upload = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
Upload.upload({
url: 'upload/url',
fields: {'username': $scope.username},
file: file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
}).success(function (data, status, headers, config) {
console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
});
}
}
};
}]);
Full reference
File select
<button|div|input type="file"|ngf-select|...
ngf-select ng-model="myFiles" // binds the selected files to the scope model
ng-model-rejected="rejFiles" // bind to dropped files that do not match the accept wildcard
ngf-change="fileSelected($files, $event)" // will be called upon files being selected
// you can use $scope.$watch('myFiles') instead
ngf-multiple="true|false" // default false, allows selecting multiple files
ngf-capture="'camera'|'other'" // allows mobile devices to capture using camera
accept="'image/*'" // see standard HTML file input accept attribute
ngf-accept="'image/*'|validate($file)" // function or comma separated wildcard to filter files allowed
ngf-min-size='10' // minimum acceptable file size in bytes
ngf-max-size='10' // maximum acceptable file size in bytes
>Upload</button>
File drop
<div|button|ngf-drop|...
ngf-drop ng-model="myFiles" // binds the dropped files to the scope model
ng-model-rejected="rejFiles" // bind to dropped files that do not match the accept wildcard
ngf-change="fileDropped($files, $event, $rejectedFiles)" //called upon files being dropped
ngf-multiple="true|false" // default false, allows selecting multiple files.
ngf-accept="'.pdf,.jpg'|validate($file)" // function or comma separated wildcard to filter files allowed
ngf-allow-dir="true|false" // default true, allow dropping files only for Chrome webkit browser
ngf-drag-over-class="{accept:'acceptClass', reject:'rejectClass', delay:100}|myDragOverClass|
calcDragOverClass($event)"
// drag over css class behaviour. could be a string, a function returning class name
// or a json object {accept: 'c1', reject: 'c2', delay:10}. default "dragover"
// reject class only works in Chrome.
ngf-drop-available="dropSupported" // set the value of scope model to true or false based on file
// drag&drop support for this browser
ngf-stop-propagation="true|false" // default false, whether to propagate drag/drop events.
ngf-hide-on-drop-not-available="true|false" // default false, hides element if file drag&drop is not supported
ngf-min-size='10' // minimum acceptable file size in bytes
ngf-max-size='10' // maximum acceptable file size in bytes
>
Drop files here
</div>
<div|... ng-no-file-drop>File Drag/drop is not supported</div>
$upload service:
var upload = Upload.upload({
*url: 'server/upload/url',
*file: file,
method: 'POST' or 'PUT', default POST,
headers: {'Authorization': 'xxx'},
fileName: 'doc.jpg' or ['1.jpg', '2.jpg', ...],
fileFormDataName: 'myFile' or ['file[0]', 'file[1]', ...],
fields: {key: $scope.myValue, ...},
sendObjectsAsJsonBlob: true|false,
formDataAppender: function(formData, key, val){},
data: {}.
withCredentials: true|false,
... and all other angular $http() options could be used here.
}).progress(function(evt) {
console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total) + '% file :'+ evt.config.file.name);
}).success(function(data, status, headers, config) {
console.log('file ' + config.file.name + 'is uploaded successfully. Response: ' + data);
}).error(...
}).xhr(function(xhr){xhr.upload.addEventListener(...)
});
var promise = upload.then(success, error, progress);
upload.abort();
Upload.http({
url: '/server/upload/url',
headers : {
'Content-Type': file.type
},
data: file
})
Upload multiple files: Only for HTML5 FormData browsers (not IE8-9) if you pass an array of files to file
option it will upload all of them together in one request. In this case the fileFormDataName
could be an array of names or a single string. For Rails or depending on your server append square brackets to the end (i.e. file[]
).
Non-html5 browsers due to flash limitation will still upload array of files one by one in a separate request. You should iterate over files and send them one by one if you want cross browser solution.
Upload.http():
This is equivalent to angular $http() but allow you to listen to the progress event for HTML5 browsers.
Rails progress event: If your server is Rails and Apache you may need to modify server configurations for the server to support upload progress. See #207
drag and drop styling: For file drag and drop, ngf-drag-over-class
could be used to style the drop zone. It can be a function that returns a class name based on the $event. Default is "dragover" string.
It could also be a json object {accept: 'a', 'reject': 'r', delay: 10}
that specify the class name for the accepted or rejected drag overs.
reject
param will only work in Chrome browser which provide information about dragged over content. However some file types are reported as empty by Chrome even though they will have correct type when they are dropped, so if your accept
attribute wildcard depends on file types rather than file extensions it may not work for those files if their type is not reported by Chrome.
delay
param is there to fix css3 transition issues from dragging over/out/over #277.
## Old browsers
For browsers not supporting HTML5 FormData (IE8, IE9, ...) FileAPI module is used.
Note: You need Flash installed on your browser since FileAPI
uses Flash to upload files.
These two files FileAPI.min.js
, FileAPI.flash.swf
will be loaded by the module on demand (no need to be included in the html) if the browser does not supports HTML5 FormData to avoid extra load for HTML5 browsers.
You can place these two files beside angular-file-upload-shim(.min).js
on your server to be loaded automatically from the same path or you can specify the path to those files if they are in a different path using the following script:
<script>
FileAPI = {
jsPath: '/js/FileAPI.min.js/folder/',
jsUrl: 'yourcdn.com/js/FileAPI.min.js',
staticPath: '/flash/FileAPI.flash.swf/folder/',
flashUrl: 'yourcdn.com/js/FileAPI.flash.swf',
}
</script>
<script src="angular-file-upload-shim.min.js"></script>...
Old browsers known issues:
- Because of a Flash limitation/bug if the server doesn't send any response body the status code of the response will be always
204 'No Content'
. So if you have access to your server upload code at least return a character in the response for the status code to work properly. - Custom headers will not work due to a Flash limitation #111 #224 #129
- Due to Flash bug #92 Server HTTP error code 400 will be returned as 200 to the client. So avoid returning 400 on your server side for upload response otherwise it will be treated as a success response on the client side.
- In case of an error response (http code >= 400) the custom error message returned from the server may not be available. For some error codes flash just provide a generic error message and ignores the response text. #310
- Older browsers won't allow
PUT
requests. #261
##Server Side
Amazon AWS S3 Upload
The demo page has an option to upload to S3.
Here is a sample config options:
$upload.upload({
url: $'https://angular-file-upload.s3.amazonaws.com/', //S3 upload url including bucket name
method: 'POST',
fields : {
key: file.name, // the key to store the file on S3, could be file name or customized
AWSAccessKeyId: <YOUR AWS AccessKey Id>,
acl: 'private', // sets the access to the uploaded file in the bucket: private or public
policy: $scope.policy, // base64-encoded json policy (see article below)
signature: $scope.signature, // base64-encoded signature based on policy string (see article below)
"Content-Type": file.type != '' ? file.type : 'application/octet-stream', // content type of the file (NotEmpty)
filename: file.name // this is needed for Flash polyfill IE8-9
},
file: file,
});
This article explain more about these fields: see http://aws.amazon.com/articles/1434/
To generate the policy and signature you need a server side tool as described this article.
These two values are generated from the json policy document which looks like this:
{"expiration": "2020-01-01T00:00:00Z",
"conditions": [
{"bucket": "angular-file-upload"},
["starts-with", "$key", ""],
{"acl": "private"},
["starts-with", "$Content-Type", ""],
["starts-with", "$filename", ""],
["content-length-range", 0, 524288000]
]
}
The demo page provide a helper tool to generate the policy and signature from you from the json policy document. Note: Please use https protocol to access demo page if you are using this tool to genenrate signature and policy to protect your aws secret key which should never be shared.
Make sure that you provide upload and CORS post to your bucket at AWS -> S3 -> bucket name -> Properties -> Edit bucket policy and Edit CORS Configuration. Samples of these two files:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "UploadFile",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::xxxx:user/xxx"
},
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::angular-file-upload/*"
},
{
"Sid": "crossdomainAccess",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::angular-file-upload/crossdomain.xml"
}
]
}
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>http://angular-file-upload.appspot.com</AllowedOrigin>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
For IE8-9 flash polyfill you need to have a crossdomain.xml file at the root of you S3 bucket. Make sure the content-type of crossdomain.xml is text/xml and you provide read access to this file in your bucket policy.
If you have Node.js there is a separate github project created by Nukul Bhasin as an example using this plugin here: https://github.com/nukulb/s3-angular-file-upload
##CORS
To support CORS upload your server needs to allow cross domain requests. You can achive that by having a filter or interceptor on your upload file server to add CORS headers to the response similar to this:
(sample java code)
httpResp.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS");
httpResp.setHeader("Access-Control-Allow-Origin", "your.other.server.com");
httpResp.setHeader("Access-Control-Allow-Headers", "Content-Type"));
For non-HTML5 IE8-9 browsers you would also need a crossdomain.xml
file at the root of your server to allow CORS for flash:
(sample xml)
<cross-domain-policy>
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="angular-file-upload.appspot.com"/>
<allow-http-request-headers-from domain="*" headers="*" secure="false"/>
</cross-domain-policy>
## Install
#### Manual download
Download latest release from here
#### Bower
bower install ng-file-upload
<script src="angular(.min).js"></script>
<script src="ng-file-upload-shim(.min).js"></script>
<script src="ng-file-upload(.min).js"></script>
#### Yeoman with bower automatic include
bower install ng-file-upload --save
bower install ng-file-upload-shim --save
bower.json
{
"dependencies": [..., "ng-file-upload-shim", "ng-file-upload", ...],
}
#### NuGet
Package is also available on NuGet: http://www.nuget.org/packages/angular-file-upload with the help of Georgios Diamantopoulos
#### NPM
npm install ng-file-upload
## Issues & Contribution
For questions, bug reports, and feature request please search through existing issue and if you don't find and answer open a new one here. If you need support send me an email to set up a session through HackHands. You can also contact me for any non public concerns.