PageRenderTime 55ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/README.md

https://gitlab.com/wuzhongdehua/ng-file-upload
Markdown | 556 lines | 487 code | 69 blank | 0 comment | 0 complexity | 7d7a0d41ebfdb3d5d45fa322bbad4dfa MD5 | raw file
  1. [![npm version](https://badge.fury.io/js/ng-file-upload.svg)](http://badge.fury.io/js/ng-file-upload)
  2. [![Downloads](http://img.shields.io/npm/dm/ng-file-upload.svg)](https://npmjs.org/package/ng-file-upload)
  3. [![Issue Stats](http://issuestats.com/github/danialfarid/ng-file-upload/badge/pr)](http://issuestats.com/github/danialfarid/ng-file-upload)
  4. [![Issue Stats](http://issuestats.com/github/danialfarid/ng-file-upload/badge/issue)](http://issuestats.com/github/danialfarid/ng-file-upload)<br/>
  5. [![PayPayl donate button](https://img.shields.io/badge/paypal-donate-yellow.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=danial%2efarid%40gmail%2ecom&lc=CA&item_name=ng%2dfile%2dupload&item_number=ng%2dfile%2dupload&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)
  6. [![Gratipay donate button](https://img.shields.io/gratipay/danialfarid.svg?label=donate)](https://gratipay.com/ng-file-upload/)
  7. ng-file-upload
  8. ===================
  9. Lightweight Angular directive to upload files.
  10. **See the <a href="https://angular-file-upload.appspot.com/" target="_blank">DEMO</a> page.** Reference docs [here](https://github.com/danialfarid/ng-file-upload/blob/master/README.md)
  11. **Migration notes**: [version 3.0.x](https://github.com/danialfarid/ng-file-upload/releases/tag/3.0.0) [version 3.1.x](https://github.com/danialfarid/ng-file-upload/releases/tag/3.1.0) [version 3.2.x](https://github.com/danialfarid/ng-file-upload/releases/tag/3.2.3) [version 4.x.x](https://github.com/danialfarid/ng-file-upload/releases/tag/4.0.0) [version 5.x.x](https://github.com/danialfarid/ng-file-upload/releases/tag/5.0.0) [version 6.x.x](https://github.com/danialfarid/ng-file-upload/releases/tag/6.0.0) [version 6.2.x](https://github.com/danialfarid/ng-file-upload/releases/tag/6.2.0) [version 7.0.x](https://github.com/danialfarid/ng-file-upload/releases/tag/7.0.0) [version 7.2.x](https://github.com/danialfarid/ng-file-upload/releases/tag/7.2.0) [version 8.0.x](https://github.com/danialfarid/ng-file-upload/releases/tag/8.0.1) [version 9.0.x](https://github.com/danialfarid/ng-file-upload/releases/tag/9.0.0)
  12. Ask questions on [StackOverflow](http://stackoverflow.com/) under the [ng-file-upload](http://stackoverflow.com/tags/ng-file-upload/) tag.<br/>
  13. For bug report or feature request please search through existing [issues](https://github.com/danialfarid/ng-file-upload/issues) first then open a new one [here](https://github.com/danialfarid/ng-file-upload/issues/new). For faster response provide steps to reprodce/versions with a jsfiddle from [here](http://jsfiddle.net/ew4jakn5/). Need paid support contact [me](mailto:danial.farid@gmail.com).<br/>
  14. Contributions are always welcome. If you like this plugin give it a thumbs up at [ngmodules](http://ngmodules.org/modules/ng-file-upload).
  15. Table of Content:
  16. * [Features](#features)
  17. * [Install](#install) ([Manual](#manual), [Bower](#bower), [NuGet](#nuget), [NPM](#npm))
  18. * [Usage](#usage)
  19. * [Old Browsers](#old_browsers)
  20. * [Server Side](#server)
  21. * [Samples](#server) ([Java](#java), [Spring](#spring), [Node.js](#node), [Rails](#rails), [PHP](#php), [.Net](#net))
  22. * [CORS](#cors)
  23. * [Amazon S3 Upload](#s3)
  24. ##<a name="features"></a> Features
  25. * file upload progress, cancel/abort
  26. * file drag and drop (html5 only)
  27. * image paste form clipboard and drag and drop from browser pages (html5 only).
  28. * image resize native and image crop through [ngImgCrop](https://github.com/alexk111/ngImgCrop). See [crop sample](http://jsfiddle.net/xxo3sk41/1/) (html5 only)
  29. * orientation fix for jpeg image files with exif orientation data
  30. * resumable uploads: pause/resume upload (html5 only)
  31. * validation on file type/size, image width/height, video/audio duration and `ng-required` support.
  32. * show thumbnail or preview of selected images/audio/videos
  33. * supports CORS and direct upload of file's binary data using `Upload.$http()`
  34. * plenty of sample server side code, available on nuget
  35. * on demand flash [FileAPI](https://github.com/mailru/FileAPI) shim loading no extra load for html5 browsers.
  36. * HTML5 FileReader.readAsDataURL shim for IE8-9
  37. ##<a name="install"></a> Install
  38. * <a name="manual"></a>**Manual**: download latest from [here](https://github.com/danialfarid/ng-file-upload-bower/releases/latest)
  39. * <a name="bower"></a>**Bower**:
  40. * `bower install ng-file-upload-shim --save`(for non html5 suppport)
  41. * `bower install ng-file-upload --save`
  42. * <a name="nuget"></a>**NuGet**: `PM> Install-Package angular-file-upload` (thanks to [Georgios Diamantopoulos](https://github.com/georgiosd))
  43. * <a name="npm"></a>**NPM**: `npm install ng-file-upload`
  44. ```html
  45. <script src="angular(.min).js"></script>
  46. <script src="ng-file-upload-shim(.min).js"></script> <!-- for no html5 browsers support -->
  47. <script src="ng-file-upload(.min).js"></script>
  48. ```
  49. ##<a name="usage"></a> Usage
  50. ###Samples:
  51. * Upload with form submit and validations: [http://jsfiddle.net/danialfarid/maqbzv15/38/](http://jsfiddle.net/danialfarid/maqbzv15/38/)
  52. * Upload multiple files one by one on file select:
  53. [http://jsfiddle.net/danialfarid/2vq88rfs/136/](http://jsfiddle.net/danialfarid/2vq88rfs/136/)
  54. * Upload multiple files in one request on file select (html5 only):
  55. [http://jsfiddle.net/danialfarid/huhjo9jm/5/](http://jsfiddle.net/danialfarid/huhjo9jm/5/)
  56. * Upload single file on file select:
  57. [http://jsfiddle.net/danialfarid/0mz6ff9o/135/](http://jsfiddle.net/danialfarid/0mz6ff9o/135/)
  58. * Drop and upload with $watch:
  59. [http://jsfiddle.net/danialfarid/s8kc7wg0/219/](http://jsfiddle.net/danialfarid/s8kc7wg0/219/)
  60. * Image Crop and Upload
  61. [http://jsfiddle.net/xxo3sk41/1/](http://jsfiddle.net/xxo3sk41/1/)
  62. ```html
  63. <script src="angular.min.js"></script>
  64. <!-- shim is needed to support non-HTML5 FormData browsers (IE8-9)-->
  65. <script src="ng-file-upload-shim.min.js"></script>
  66. <script src="ng-file-upload.min.js"></script>
  67. Upload on form submit or button click
  68. <form ng-app="fileUpload" ng-controller="MyCtrl" name="form">
  69. Single Image with validations
  70. <div class="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'"
  71. accept="image/*" ngf-max-size="20MB" ngf-min-height="100"
  72. ngf-resize="{width: 100, height: 100}">Select</div>
  73. Multiple files
  74. <div class="button" ngf-select ng-model="files" ngf-multiple="true">Select</div>
  75. Drop files: <div ngf-drop ng-model="files" class="drop-box">Drop</div>
  76. <button type="submit" ng-click="submit()">submit</button>
  77. </form>
  78. Upload right away after file selection:
  79. <div class="button" ngf-select="upload($file)">Upload on file select</div>
  80. <div class="button" ngf-select="uploadFiles($files)" multiple="multiple">Upload on file select</div>
  81. Drop File:
  82. <div ngf-drop="uploadFiles($files)" class="drop-box"
  83. ngf-drag-over-class="'dragover'" ngf-multiple="true"
  84. ngf-pattern="'image/*,application/pdf'">Drop Images or PDFs files here</div>
  85. <div ngf-no-file-drop>File Drag/Drop is not supported for this browser</div>
  86. Image thumbnail: <img ngf-thumbnail="file || '/thumb.jpg'">
  87. Audio preview: <audio controls ngf-src="file"></audio>
  88. Video preview: <video controls ngf-src="file"></video>
  89. ```
  90. Javascript code:
  91. ```js
  92. //inject directives and services.
  93. var app = angular.module('fileUpload', ['ngFileUpload']);
  94. app.controller('MyCtrl', ['$scope', 'Upload', function ($scope, Upload) {
  95. // upload later on form submit or something similar
  96. $scope.submit = function() {
  97. if (form.file.$valid && $scope.file) {
  98. $scope.upload($scope.file);
  99. }
  100. };
  101. // upload on file select or drop
  102. $scope.upload = function (file) {
  103. Upload.upload({
  104. url: 'upload/url',
  105. data: {file: file, 'username': $scope.username}
  106. }).then(function (resp) {
  107. console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
  108. }, function (resp) {
  109. console.log('Error status: ' + resp.status);
  110. }, function (evt) {
  111. var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
  112. console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
  113. });
  114. };
  115. // for multiple files:
  116. $scope.uploadFiles = function (files) {
  117. if (files && files.length) {
  118. for (var i = 0; i < files.length; i++) {
  119. Upload.upload({..., data: {file: files[i]}, ...})...;
  120. }
  121. // or send them all together for HTML5 browsers:
  122. Upload.upload({..., data: {file: files}, ...})...;
  123. }
  124. }
  125. }]);
  126. ```
  127. ### Full reference
  128. #### File select and drop
  129. At least one of the `ngf-select` or `ngf-drop` are mandatory for the plugin to link to the element.
  130. `ngf-select` only attributes are marked with * and `ngf-drop` only attributes are marked with +.
  131. ```html
  132. <div|button|input type="file"|ngf-select|ngf-drop...
  133. ngf-select="" or "upload($files, ...)" // called when files are selected or cleared
  134. ngf-drop="" or "upload($files, ...)" // called when files being dropped
  135. // You can use ng-model or ngf-change instead of specifying function for ngf-drop and ngf-select
  136. // function parameters are the same as ngf-change
  137. ngf-change="upload($files, $file, $newFiles, $duplicateFiles, $invalidFiles, $event)"
  138. // called when files are selected, dropped, or cleared
  139. ng-model="myFiles" // binds the valid selected/dropped file or files to the scope model
  140. // could be an array or single file depending on ngf-multiple and ngf-keep values.
  141. ng-model-options="{updateOn: 'change click drop paste', allowInvalid: false, debounce: 0}" // angular
  142. // model options. updateOn could be used to disable resetting on click, or updating on paste, etc.
  143. // allowInvalid default is false could allow invalid files in the model
  144. // debouncing will postpone model update (miliseconds). See angular ng-model-options for more details.
  145. ngf-model-invalid="invalidFilesArray" // binds the invalid selected/dropped files to this model.
  146. ng-disabled="boolean" // disables this element
  147. ngf-select-disabled="boolean" // default false, disables file select on this element
  148. ngf-drop-disabled="boolean" // default false, disables file drop on this element
  149. ngf-multiple="boolean" // default false, allows selecting multiple files
  150. ngf-keep="true|false|'distinct'" // default false, keep the previous ng-model files and
  151. // append the new files. "'distinct'" removes duplicate files
  152. // $newFiles and $duplicateFiles are set in ngf-change/select/drop functions.
  153. ngf-fix-orientation="boolean" //default true, would rotate the jpeg image files that have
  154. // exif orientation data. See #745
  155. *ngf-capture="'camera'" or "'other'" // allows mobile devices to capture using camera
  156. *accept="image/*" // standard HTML accept attribute for the browser specific popup window filtering
  157. +ngf-allow-dir="boolean" // default true, allow dropping files only for Chrome webkit browser
  158. +ngf-drag-over-class="{pattern: 'image/*', accept:'acceptClass', reject:'rejectClass', delay:100}"
  159. or "'myDragOverClass'" or "calcDragOverClass($event)"
  160. // default "dragover". drag over css class behaviour. could be a string, a function
  161. // returning class name or a json object.
  162. // accept/reject class only works in Chrome, validating only the file mime type.
  163. // if pattern is not specified ngf-pattern will be used. See following docs for more info.
  164. +ngf-drag="drag($isDragging, $class, $event)" // function called on drag over/leave events.
  165. // $isDragging: boolean true if is dragging over(dragover), false if drag has left (dragleave)
  166. // $class is the class that is being set for the element calculated by ngf-drag-over-class
  167. +ngf-drop-available="dropSupported" // set the value of scope model to true or false based on file
  168. // drag&drop support for this browser
  169. +ngf-stop-propagation="boolean" // default false, whether to propagate drag/drop events.
  170. +ngf-hide-on-drop-not-available="boolean" // default false, hides element if file drag&drop is not
  171. ngf-resize="{width: 100, height: 100, quality: .8}" // resizes the image to the given
  172. //width, height and quality (optional between 0.1 and 1.0)
  173. //validations:
  174. ngf-pattern="'.pdf,.jpg,video/*,!.jog'" // comma separated wildcard to filter file names and types allowed
  175. // you can exclude specific files by ! at the beginning.
  176. // validate error name: pattern
  177. ngf-min-size, ngf-max-size="100" in bytes or "'10KB'" or "'10MB'" or "'10GB'"
  178. // validate as form.file.$error.maxSize=true and file.$error='maxSize'
  179. ngf-min-height, ngf-max-height, ngf-min-width, ngf-max-width="1000" in pixels only images
  180. // validate error name: maxHeight
  181. ngf-ratio="9x6,1.6" list of comma separated valid aspect ratio of images in float or 3x2 format
  182. // validate error name: ratio
  183. ngf-min-duration, ngf-max-duration="100.5" in seconds or "'10s'" or "'10m'" or "'10h'" only audio, video
  184. // validate error name: maxDuration
  185. ngf-validate="{size: {min: 10, max: '20MB'}, width: {min: 100, max:10000}, height: {min: 100, max: 300}
  186. ratio: '2x1', duration: {min: '10s', max: '5m'}, pattern: '.jpg'}"
  187. shorthand form for above validations in one place.
  188. ngf-validate-fn="validate($file)" // custom validation function, return boolean or string containing the error.
  189. // validate error name: validateFn
  190. ngf-validate-async-fn="validate($file)" // custom validation function, return a promise that resolve to
  191. // boolean or string containing the error. validate error name: validateAsyncFn
  192. ngf-validate-force="boolean" // default false, if true file.$error will be set if the dimension or duration
  193. // values for validations cannot be calculated for example image load error or unsupported video by the browser.
  194. // by default it would assume the file is valid if the duration or dimension cannot be calculated by the browser.
  195. >Upload/Drop</div>
  196. <div|... ngf-no-file-drop>File Drag/drop is not supported</div>
  197. ```
  198. #### File preview
  199. ```html
  200. <img|audio|video|div
  201. *ngf-src="file" //To preview the selected file, sets src attribute to the file data url.
  202. *ngf-background="file" //sets background-image style to the file data url.
  203. ngf-resize="{width: 20, height: 20, quality: 0.9}" // only for image resizes the image before setting it
  204. // as src or background image. quality is optional.
  205. ngf-no-object-url="true or false" // see #887 to force base64 url generation instead of object url. Default false
  206. >
  207. <div|span|...
  208. *ngf-thumbnail="file" //Generates a thumbnail version of the image file
  209. ngf-size="{width: 20, height: 20, quality: 0.9}" the image will be resized to this size
  210. // if not specified will be resized to this element`s client width and height.
  211. ngf-as-background="boolean" //if true it will set the background image style instead of src attribute.
  212. >
  213. ```
  214. #### Upload service:
  215. ```js
  216. var upload = Upload.upload({
  217. *url: 'server/upload/url', // upload.php script, node.js route, or servlet url
  218. /*
  219. Specify the file and optional data to be sent to the server.
  220. Each field including nested objects will be sent as a form data multipart.
  221. Samples: {pic: file, username: username}
  222. {files: files, otherInfo: {id: id, person: person,...}} multiple files (html5)
  223. {profiles: {[{pic: file1, username: username1}, {pic: file2, username: username2}]} nested array multiple files (html5)
  224. {file: file, info: Upload.json({id: id, name: name, ...})} send fields as json string
  225. {file: file, info: Upload.jsonBlob({id: id, name: name, ...})} send fields as json blob
  226. {picFile: Upload.rename(file, 'profile.jpg'), title: title} send file with picFile key and profile.jpg file name*/
  227. *data: {key: file, otherInfo: uploadInfo},
  228. /*
  229. This is to accommodate server implementations expecting nested data object keys in .key or [key] format.
  230. Example: data: {rec: {name: 'N', pic: file}} sent as: rec[name] -> N, rec[pic] -> file
  231. data: {rec: {name: 'N', pic: file}, objectKey: '.k'} sent as: rec.name -> N, rec.pic -> file */
  232. objectKey: '[k]' or '.k' // default is '[k]'
  233. /*
  234. This is to accommodate server implementations expecting array data object keys in '[i]' or '[]' or
  235. ''(multiple entries with same key) format.
  236. Example: data: {rec: [file[0], file[1], ...]} sent as: rec[0] -> file[0], rec[1] -> file[1],...
  237. data: {rec: {rec: [f[0], f[1], ...], arrayKey: '[]'} sent as: rec[] -> f[0], rec[] -> f[1],...*/
  238. arrayKey: '[i]' or '[]' or '.i' or '' //default is '[i]'
  239. method: 'POST' or 'PUT'(html5), default POST,
  240. headers: {'Authorization': 'xxx'}, // only for html5
  241. withCredentials: boolean,
  242. /*
  243. See resumable upload guide below the code for more details (html5 only) */
  244. resumeSizeUrl: '/uploaded/size/url?file=' + file.name // uploaded file size so far on the server.
  245. resumeSizeResponseReader: function(data) {return data.size;} // reads the uploaded file size from resumeSizeUrl GET response
  246. resumeSize: function() {return promise;} // function that returns a prommise which will be
  247. // resolved to the upload file size on the server.
  248. resumeChunkSize: 10000 or '10KB' or '10MB' // upload in chunks of specified size
  249. disableProgress: boolean // default false, experimental as hotfix for potential library conflicts with other plugins
  250. ... and all other angular $http() options could be used here.
  251. })
  252. // returns a promise
  253. upload.then(function(resp) {
  254. // file is uploaded successfully
  255. console.log('file ' + resp.config.data.file.name + 'is uploaded successfully. Response: ' + resp.data);
  256. }, function(resp) {
  257. // handle error
  258. }, function(evt) {
  259. // progress notify
  260. console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total) + '% file :'+ evt.config.data.file.name);
  261. });
  262. upload.catch(errorCallback);
  263. upload.finally(callback, notifyCallback);
  264. /* access or attach event listeners to the underlying XMLHttpRequest */
  265. upload.xhr(function(xhr){
  266. xhr.upload.addEventListener(...)
  267. });
  268. /* cancel/abort the upload in progress. */
  269. upload.abort();
  270. /*
  271. alternative way of uploading, send the file binary with the file's content-type.
  272. Could be used to upload files to CouchDB, imgur, etc... html5 FileReader is needed.
  273. This is equivalent to angular $http() but allow you to listen to the progress event for HTML5 browsers.*/
  274. Upload.http({
  275. url: '/server/upload/url',
  276. headers : {
  277. 'Content-Type': file.type
  278. },
  279. data: file
  280. })
  281. /* Set the default values for ngf-select and ngf-drop directives*/
  282. Upload.setDefaults({ngfMinSize: 20000, ngfMaxSize:20000000, ...})
  283. /* Convert a single file or array of files to a single or array of
  284. base64 data url representation of the file(s).
  285. Could be used to send file in base64 format inside json to the databases */
  286. Upload.base64DataUrl(files).then(function(urls){...});
  287. /* Convert the file to blob url object or base64 data url based on boolean disallowObjectUrl value */
  288. Upload.dataUrl(file, boolean).then(function(url){...});
  289. /* Get image file dimensions*/
  290. Upload.imageDimensions(file).then(function(dimensions){console.log(dimensions.width, dimensions.height);});
  291. /* Get audio/video duration*/
  292. Upload.mediaDuration(file).then(function(durationInSeconds){...});
  293. /* returns boolean showing if image resize is supported by this browser*/
  294. Upload.isResizeSupported()
  295. /* returns boolean showing if resumable upload is supported by this browser*/
  296. Upload.isResumeSupported()
  297. /* returns a file which will be uploaded with the newName instead of original file name */
  298. Upload.rename(file, newName)
  299. /* converts the object to a Blob object with application/json content type
  300. for jsob byte streaming support #359 */
  301. Upload.json(obj)
  302. /* converts the value to json to send data as json string. Same as angular.toJson(obj) */
  303. Upload.json(obj)
  304. ```
  305. **ng-model**
  306. The model value will be a single file instead of an array if all of the followings are true:
  307. * `ngf-multiple` is not set or is resolved to false.
  308. * `multiple` attribute is not set on the element
  309. * `ngf-keep` is not set or is resolved to false.
  310. **validation**
  311. When any of the validation directives specified the form validation will take place and
  312. you can access the value of the validation using `myForm.myFileInputName.$error.<validate error name>`
  313. for example `form.file.$error.pattern`.
  314. If multiple file selection is allowed you can specify `ngf-model-invalid="invalidFiles"` to assing the invalid files to
  315. a model and find the error of each individual file with `file.$error` and description of it with `file.$errorParam`.
  316. You can use angular ng-model-options to allow invalid files to be set to the ng-model `ng-model-options="{allowInvalid: true}"`.
  317. **Upload multiple files**: Only for HTML5 FormData browsers (not IE8-9) you have an array of files or more than one file in your `data` to
  318. send them all in one request . Non-html5 browsers due to flash limitation will upload each file one by one in a separate request.
  319. You should iterate over the files and send them one by one for a cross browser solution.
  320. **drag and drop styling**: For file drag and drop, `ngf-drag-over-class` could be used to style the drop zone.
  321. It can be a function that returns a class name based on the $event. Default is "dragover" string.
  322. Only in chrome It could be a json object `{accept: 'a', 'reject': 'r', pattern: 'image/*', delay: 10}` that specify the
  323. class name for the accepted or rejected drag overs. The `pattern` specified or `ngf-pattern` will be used to validate the file's `mime-type`
  324. since that is the only property of the file that is reported by the browser on drag. So you cannot validate
  325. the file name/extension, size or other validations on drag. There is also some limitation on some file types which are not reported by Chrome.
  326. `delay` default is 100, and is used to fix css3 transition issues from dragging over/out/over [#277](https://github.com/danialfarid/angular-file-upload/issues/277).
  327. **Upload.setDefaults()**:
  328. If you have many file selects or drops you can set the default values for the directives by calling `Upload.setDefaults(options)`. `options` would be a json object with directive names in camelcase and their default values.
  329. **Resumable Uploads**
  330. The plugin supports resumable uploads for large files.
  331. On your server you need to keep track of what files are being uploaded and how much of the file is uploaded.
  332. * `url` upload endpoint need to reassemble the file chunks by appending uploading content to the end of the file or correct chunk position if it already exists.
  333. * `resumeSizeUrl` server endpoint to return uploaded file size so far on the server to be able to resume the upload from
  334. where it is ended. It should return zero if the file has not been uploaded yet. <br/>A GET request will be made to that
  335. url for each upload to determine if part of the file is already uploaded or not. You need a unique way of identifying the file
  336. on the server so you can pass the file name or generated id for the file as a request parameter.<br/>
  337. By default it will assume that the response
  338. content is an integer or a json object with `size` integer property. If you return other formats from the endpoint you can specify
  339. `resumeSizeResponseReader` function to return the size value from the response. Alternatively instead of `resumeSizeUrl` you can use
  340. `resumeSize` function which returns a promise that resolves to the size of the uploaded file so far.
  341. Make sure when the file is fully uploaded without any error/abort this endpoint returns zero for the file size
  342. if you want to let the user to upload the same file again. Or optionally you could have a restart endpoint to
  343. set that back to zero to allow re-uploading the same file.
  344. * Optionally you can specify `resumeChunkSize` to upload the file in chunks to the server. This will allow uploading to GAE or other servers that have
  345. file size limitation and trying to upload the whole request before passing it for internal processing.<br/>
  346. If this option is set the requests will have three extra fields:
  347. `_chunckSize`, `_chunkNumber` (zero starting), and `_totalSize` to help the server to write the uploaded chunk to
  348. the correct position.
  349. Uploading in chunks could slow down the overall upload time specially if the chunk size is too small.
  350. ##<a name="old_browsers"></a> Old browsers
  351. For browsers not supporting HTML5 FormData (IE8, IE9, ...) [FileAPI](https://github.com/mailru/FileAPI) module is used.
  352. **Note**: You need Flash installed on your browser since `FileAPI` uses Flash to upload files.
  353. 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.
  354. 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:
  355. ```html
  356. <script>
  357. //optional need to be loaded before angular-file-upload-shim(.min).js
  358. FileAPI = {
  359. //only one of jsPath or jsUrl.
  360. jsPath: '/js/FileAPI.min.js/folder/',
  361. jsUrl: 'yourcdn.com/js/FileAPI.min.js',
  362. //only one of staticPath or flashUrl.
  363. staticPath: '/flash/FileAPI.flash.swf/folder/',
  364. flashUrl: 'yourcdn.com/js/FileAPI.flash.swf',
  365. //forceLoad: true, html5: false //to debug flash in HTML5 browsers
  366. //noContentTimeout: 10000 (see #528)
  367. }
  368. </script>
  369. <script src="angular-file-upload-shim.min.js"></script>...
  370. ```
  371. **Old browsers known issues**:
  372. * 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.
  373. * Custom headers will not work due to a Flash limitation [#111](https://github.com/danialfarid/ng-file-upload/issues/111) [#224](https://github.com/danialfarid/ng-file-upload/issues/224) [#129](https://github.com/danialfarid/ng-file-upload/issues/129)
  374. * Due to Flash bug [#92](https://github.com/danialfarid/ng-file-upload/issues/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.
  375. * 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](https://github.com/danialfarid/ng-file-upload/issues/310)
  376. * Older browsers won't allow `PUT` requests. [#261](https://github.com/danialfarid/ng-file-upload/issues/261)
  377. ##<a name="server"></a>Server Side
  378. * <a name="java"></a>**Java**
  379. You can find the sample server code in Java/GAE [here](https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/java/com/df/angularfileupload/)
  380. * <a name="spring"></a>**Spring MVC**
  381. [Wiki Sample](https://github.com/danialfarid/ng-file-upload/wiki/spring-mvc-example) provided by [zouroto](https://github.com/zouroto)
  382. * <a name="node"></a>**Node.js**
  383. [Wiki Sample](https://github.com/danialfarid/ng-file-upload/wiki/node.js-example) provided by [chovy](https://github.com/chovy).
  384. [Another wiki](https://github.com/danialfarid/ng-file-upload/wiki/Node-example) using Express 4.0 and the Multiparty provided by [Jonathan White](https://github.com/JonathanZWhite)
  385. * <a name="rails"></a>**Rails**
  386. * [Wiki Sample](https://github.com/danialfarid/ng-file-upload/wiki/Rails-Example) provided by [guptapriyank](https://github.com/guptapriyank).
  387. * [Blog post](http://www.coshx.com/blog/2015/07/10/file-attachments-in-angular/)
  388. provided by [Coshx Labs](http://www.coshx.com/).
  389. * **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](https://github.com/danialfarid/ng-file-upload/issues/207)
  390. * <a name="php"></a>**PHP**
  391. [Wiki Sample] (https://github.com/danialfarid/ng-file-upload/wiki/PHP-Example) and related issue [only one file in $_FILES when uploading multiple files] (https://github.com/danialfarid/ng-file-upload/issues/475)
  392. * <a name="net"></a>**.Net**
  393. Sample client and server code [demo/C#] (https://github.com/danialfarid/ng-file-upload/tree/master/demo/C%23) provided by [AtomStar](https://github.com/AtomStar)
  394. ##<a name="cors"></a>CORS
  395. 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:
  396. ([sample java code](https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/java/com/df/angularfileupload/CORSFilter.java))
  397. ```java
  398. httpResp.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS");
  399. httpResp.setHeader("Access-Control-Allow-Origin", "your.other.server.com");
  400. httpResp.setHeader("Access-Control-Allow-Headers", "Content-Type"));
  401. ```
  402. 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:
  403. <a name="crossdomain"></a>([sample xml](https://angular-file-upload.appspot.com/crossdomain.xml))
  404. ```xml
  405. <cross-domain-policy>
  406. <site-control permitted-cross-domain-policies="all"/>
  407. <allow-access-from domain="angular-file-upload.appspot.com"/>
  408. <allow-http-request-headers-from domain="*" headers="*" secure="false"/>
  409. </cross-domain-policy>
  410. ```
  411. #### <a name="s3"></a>Amazon AWS S3 Upload
  412. The <a href="https://angular-file-upload.appspot.com/" target="_blank">demo</a> page has an option to upload to S3.
  413. Here is a sample config options:
  414. ```js
  415. Upload.upload({
  416. url: 'https://angular-file-upload.s3.amazonaws.com/', //S3 upload url including bucket name
  417. method: 'POST',
  418. data: {
  419. key: file.name, // the key to store the file on S3, could be file name or customized
  420. AWSAccessKeyId: <YOUR AWS AccessKey Id>,
  421. acl: 'private', // sets the access to the uploaded file in the bucket: private, public-read, ...
  422. policy: $scope.policy, // base64-encoded json policy (see article below)
  423. signature: $scope.signature, // base64-encoded signature based on policy string (see article below)
  424. "Content-Type": file.type != '' ? file.type : 'application/octet-stream', // content type of the file (NotEmpty)
  425. filename: file.name, // this is needed for Flash polyfill IE8-9
  426. file: file
  427. }
  428. });
  429. ```
  430. [This article](http://aws.amazon.com/articles/1434/) explains more about these fields and provides instructions on how to generate the policy and signature using a server side tool.
  431. These two values are generated from the json policy document which looks like this:
  432. ```js
  433. {
  434. "expiration": "2020-01-01T00:00:00Z",
  435. "conditions": [
  436. {"bucket": "angular-file-upload"},
  437. ["starts-with", "$key", ""],
  438. {"acl": "private"},
  439. ["starts-with", "$Content-Type", ""],
  440. ["starts-with", "$filename", ""],
  441. ["content-length-range", 0, 524288000]
  442. ]
  443. }
  444. ```
  445. The [demo](https://angular-file-upload.appspot.com/) 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 generate signature and policy to protect your aws secret key which should never be shared.
  446. 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:
  447. ```js
  448. {
  449. "Version": "2012-10-17",
  450. "Statement": [
  451. {
  452. "Sid": "UploadFile",
  453. "Effect": "Allow",
  454. "Principal": {
  455. "AWS": "arn:aws:iam::xxxx:user/xxx"
  456. },
  457. "Action": [
  458. "s3:GetObject",
  459. "s3:PutObject"
  460. ],
  461. "Resource": "arn:aws:s3:::angular-file-upload/*"
  462. },
  463. {
  464. "Sid": "crossdomainAccess",
  465. "Effect": "Allow",
  466. "Principal": "*",
  467. "Action": "s3:GetObject",
  468. "Resource": "arn:aws:s3:::angular-file-upload/crossdomain.xml"
  469. }
  470. ]
  471. }
  472. ```
  473. ```xml
  474. <?xml version="1.0" encoding="UTF-8"?>
  475. <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  476. <CORSRule>
  477. <AllowedOrigin>http://angular-file-upload.appspot.com</AllowedOrigin>
  478. <AllowedMethod>POST</AllowedMethod>
  479. <AllowedMethod>GET</AllowedMethod>
  480. <AllowedMethod>HEAD</AllowedMethod>
  481. <MaxAgeSeconds>3000</MaxAgeSeconds>
  482. <AllowedHeader>*</AllowedHeader>
  483. </CORSRule>
  484. </CORSConfiguration>
  485. ```
  486. For IE8-9 flash polyfill you need to have a <a href='#crossdomain'>crossdomain.xml</a> 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.
  487. You can also have a look at [https://github.com/nukulb/s3-angular-file-upload](https://github.com/nukulb/s3-angular-file-upload) for another example with [this](https://github.com/danialfarid/ng-file-upload/issues/814#issuecomment-112198426) fix.