banner



How Upload Files To Github

npm version Downloads Issue Stats Issue Stats
PayPayl donate button Gratipay donate button

ng-file-upload

Lightweight Angular directive to upload files.

Meet the DEMO page. Reference docs hither

Migration notes: version 3.0.10 version 3.1.x version iii.2.ten version 4.x.x version 5.x.ten version 6.ten.ten version half dozen.2.x version vii.0.x version 7.ii.x version 8.0.x version 9.0.10 version x.0.x version 11.0.x version 12.0.x version 12.i.x version 12.2.x

Inquire questions on StackOverflow under the ng-file-upload tag.
For bug report or characteristic request delight search through existing bug first and then open up a new one here. For faster response provide steps to reproduce/versions with a jsfiddle link. If yous need support for your company contact me.
If yous like this plugin give it a thumbs upward at ngmodules or get me a cup of tea . Contributions are welcomed.

Table of Content:

  • Features
  • Install (Manual, Bower, NuGet, NPM)
  • Usage
  • Old Browsers
  • Server Side
    • Samples (Java, Spring, Node.js, Rail, PHP, .Net)
    • CORS
    • Amazon S3 Upload

Features

  • file upload progress, cancel/abort
  • file drag and drop (html5 simply)
  • image paste from clipboard and elevate and drop from browser pages (html5 just).
  • image resize and center ingather (native) and user controlled crop through ngImgCrop. Meet crop sample (html5 only)
  • orientation fix for jpeg image files with exif orientation data
  • resumable uploads: intermission/resume upload (html5 but)
  • native validation support for file type/size, image width/height/aspect ratio, video/audio duration, and ng-required with pluggable custom sync or async validations.
  • bear witness thumbnail or preview of selected images/audio/videos
  • supports CORS and direct upload of file'southward binary data using Upload.$http()
  • plenty of sample server side lawmaking, available on nuget
  • on demand wink FileAPI shim loading no actress load for html5 browsers.
  • HTML5 FileReader.readAsDataURL shim for IE8-9
  • bachelor on npm, bower, meteor, nuget

Install

  • Manual: download latest from hither
  • Bower:
    • bower install ng-file-upload-shim --save(for non html5 suppport)
    • bower install ng-file-upload --save
  • NuGet: PM> Install-Parcel athwart-file-upload (thanks to Georgios Diamantopoulos)
  • NPM: npm install ng-file-upload
              <              script              src="angular(.min).js">              </              script              >              <              script              src="ng-file-upload-shim(.min).js">              </              script              >              <!-- for no html5 browsers back up -->              <              script              src="ng-file-upload(.min).js">              </              script              >            

Usage

Samples:

  • Upload with class submit and validations: http://jsfiddle.internet/danialfarid/maqbzv15/1118/
  • Upload multiple files i past ane on file select: http://jsfiddle.net/danialfarid/2vq88rfs/136/
  • Upload multiple files in i request on file select (html5 only): http://jsfiddle.net/danialfarid/huhjo9jm/five/
  • Upload single file on file select: http://jsfiddle.net/danialfarid/0mz6ff9o/135/
  • Drop and upload with $watch: http://jsfiddle.internet/danialfarid/s8kc7wg0/400/
  • Prototype Crop and Upload http://jsfiddle.cyberspace/danialfarid/xxo3sk41/590/
              <              script              src="angular.min.js">              </              script              >              <!-- shim is needed to support non-HTML5 FormData browsers (IE8-9)-->              <              script              src="ng-file-upload-shim.min.js">              </              script              >              <              script              src="ng-file-upload.min.js">              </              script              >              Upload on form submit or button click              <              form              ng-app="fileUpload"              ng-controller="MyCtrl"              name="course">              Single Image with validations              <              div              form="button"              ngf-select              ng-model="file"              name="file"              ngf-pattern="'image/*'"              ngf-accept="'image/*'"              ngf-max-size="20MB"              ngf-min-meridian="100"              ngf-resize="{width: 100, meridian: 100}">Select</              div              >              Multiple files              <              div              class="button"              ngf-select              ng-model="files"              ngf-multiple="truthful">Select</              div              >              Drop files:              <              div              ngf-drop              ng-model="files"              course="drop-box">Driblet</              div              >              <              button              type="submit"              ng-click="submit()">submit</              button              >              </              grade              >              Upload right away after file selection:              <              div              class="push button"              ngf-select="upload($file)">Upload on file select</              div              >              <              div              course="button"              ngf-select="uploadFiles($files)"              multiple="multiple">Upload on file select</              div              >              Drop File:              <              div              ngf-drop="uploadFiles($files)"              class="driblet-box"              ngf-elevate-over-class="'dragover'"              ngf-multiple="true"              ngf-blueprint="'image/*,awarding/pdf'">Drop Images or PDFs files hither</              div              >              <              div              ngf-no-file-drop              >File Drag/Drop is non supported for this browser</              div              >              Image thumbnail:              <              img              ngf-thumbnail="file || '/thumb.jpg'">              Audio preview:              <              audio              controls              ngf-src="file">              </              audio              >              Video preview:              <              video              controls              ngf-src="file">              </              video              >            

Javascript code:

              //inject directives and services.              var              app              =              angular              .              module              (              'fileUpload'              ,              [              'ngFileUpload'              ]              )              ;              app              .              controller              (              'MyCtrl'              ,              [              '$scope'              ,              'Upload'              ,              function              (              $telescopic              ,              Upload              )              {              // upload later on on grade submit or something like              $scope              .              submit              =              function              (              )              {              if              (              $telescopic              .              form              .              file              .              $valid              &&              $scope              .              file              )              {              $telescopic              .              upload              (              $scope              .              file              )              ;              }              }              ;              // upload on file select or drop              $scope              .              upload              =              role              (              file              )              {              Upload              .              upload              (              {              url:              'upload/url'              ,              data:              {              file:              file              ,              'username':              $telescopic              .              username              }              }              )              .              then              (              function              (              resp              )              {              panel              .              log              (              'Success '              +              resp              .              config              .              data              .              file              .              name              +              'uploaded. Response: '              +              resp              .              information              )              ;              }              ,              function              (              resp              )              {              console              .              log              (              'Fault status: '              +              resp              .              condition              )              ;              }              ,              function              (              evt              )              {              var              progressPercentage              =              parseInt              (              100.0              *              evt              .              loaded              /              evt              .              full              )              ;              console              .              log              (              'progress: '              +              progressPercentage              +              '% '              +              evt              .              config              .              data              .              file              .              name              )              ;              }              )              ;              }              ;              // for multiple files:              $scope              .              uploadFiles              =              part              (              files              )              {              if              (              files              &&              files              .              length              )              {              for              (              var              i              =              0              ;              i              <              files              .              length              ;              i              ++              )              {              Upload              .              upload              (              {...,              data:              {              file:              files              [              i              ]              }              ,              ...}              )              .              .              .              ;              }              // or send them all together for HTML5 browsers:              Upload              .              upload              (              {...,              data:              {              file:              files              }              ,              ...}              )              .              .              .              ;              }              }              }              ]              )              ;            

Full reference

File select and drop

At least one of the ngf-select or ngf-drop are mandatory for the plugin to link to the element. ngf-select only attributes are marked with * and ngf-drop only attributes are marked with +.

              <              div              |push|input              type="file"|ngf-select|ngf-drop...              ngf-select=""              or              "upload($files, ...)"              <!-- chosen when files are selected or cleared -->              ngf-drop=""              or              "upload($files, ...)"              <!--  called when files being dropped                              You can apply ng-model or ngf-modify instead of specifying function for ngf-drop and ngf-select                              part parameters are the same equally ngf-alter -->              ngf-modify="upload($files, $file, $newFiles, $duplicateFiles, $invalidFiles, $outcome)"              <!--  called when files are selected, dropped, or cleared -->              ng-model="myFiles"              <!--  binds the valid selected/dropped file or files to the scope model                              could be an array or unmarried file depending on ngf-multiple and ngf-continue values. -->              ngf-model-options="{updateOn: 'change click drop dropUrl paste', allowInvalid: false, debounce: 0}"              <!--  updateOn could be used to disable resetting on click, or updating on paste, browser                                            image drop, etc. allowInvalid default is simulated could let invalid files in the model                              debouncing will postpone model update (miliseconds). See athwart ng-model-options for more details. -->              ngf-model-invalid="invalidFile(s)"              <!--  binds the invalid selected/dropped file or files to this model. -->              ngf-earlier-model-change="beforeChange($files, ...)"              <!--  called after file select/drop and before                              model modify, validation and resize is processed -->              ng-disabled="boolean"              <!--  disables this chemical element -->              ngf-select-disabled="boolean"              <!--  default faux, disables file select on this element -->              ngf-drop-disabled="boolean"              <!--  default false, disables file driblet on this element -->              ngf-multiple="boolean"              <!--  default false, allows selecting multiple files -->              ngf-keep="true|false|'distinct'"              <!--  default false, keep the previous ng-model files and                                            append the new files. "'distinct'" removes duplicate files                              $newFiles and $duplicateFiles are set in ngf-change/select/driblet functions. -->              ngf-fix-orientation="boolean"              <!-- default faux, would rotate the jpeg image files that have                              exif orientation data. Run across #745. Could be a boolean role like shouldFixOrientation($file)                              to decide wethere to prepare that file or not. -->              *ngf-capture="'photographic camera'"              or              "'other'"              <!--  allows mobile devices to capture using camera -->              *ngf-accept="'paradigm/*'"              <!--  standard HTML accept attr, browser specific select popup window -->              +ngf-permit-dir="boolean"              <!--  default true, allow dropping files only for Chrome webkit browser -->              +ngf-include-dir="boolean"              <!-- default false, include directories in the dropped file assortment.                              Y'all can detect if they are directory or not past checking the type === 'directory'. -->              +ngf-elevate-over-class="{pattern: 'image/*', have:'acceptClass', decline:'rejectClass', delay:100}"              or              "'myDragOverClass'" or "calcDragOverClass($consequence)"              <!--  default "dragover". drag over css class behaviour. could be a string, a part                              returning class name or a json object.                              accept/reject class only works in Chrome, validating but the file mime type.                              if blueprint is not specified ngf-design volition be used. See following docs for more than info. -->              +ngf-drag="drag($isDragging, $form, $event)"              <!--  part called on drag over/exit events.                              $isDragging: boolean true if is dragging over(dragover), simulated if drag has left (dragleave)                              $class is the form that is beingness prepare for the element calculated by ngf-drag-over-class -->              +ngf-drop-bachelor="dropSupported"              <!--  set up the value of scope model to truthful or false                                            based on file drag&drop support for this browser -->              +ngf-stop-propagation="boolean"              <!--  default false, whether to propagate drag/drop events. -->              +ngf-hibernate-on-driblet-non-available="boolean"              <!--  default false, hides chemical element if file drag&drop is not -->              +ngf-enable-firefox-paste="boolean"              <!--  *experimental* default false, enable firefox paradigm paste                                            by making element contenteditable -->              ngf-resize="{width: 100, height: 100, quality: .8, type: 'image/jpeg',                              ratio: 'ane:2', centerCrop: true, pattern='.jpg', restoreExif: false}"              or              resizeOptions()              <!--  a role returning a promise which resolves into the options.                              resizes the image to the given width/meridian or ratio. Quality is optional betwixt 0.i and 1.0),                              type is optional convert information technology to the given image type format.                              centerCrop true volition center crop the prototype if it does not fit within the given width/acme or ratio.                              centerCrop fake (default) volition not crop the image and volition fit it within the given width/height or ratio                              and so the resulting epitome width (or pinnacle) could be less than given width (or height).                              pattern is to resize just the files that their name or blazon matches the design similar to ngf-pattern.                              restoreExif boolean default true, will restore exif info on the resized image. -->              ngf-resize-if="$width > one thousand || $summit > 1000"              or              "resizeCondition($file, $width, $height)"              <!--  apply ngf-resize only if this function returns true. To filter specific images to exist resized. -->              ngf-validate-after-resize="boolean"              <!--  default false, if true all validation will be run after                              the images are being resized, so whatever validation error earlier resize will be ignored. -->              <!-- validations: -->              ngf-max-files="10"              <!--  maximum number of files allowed to be selected or dropped, validate error proper name: maxFiles -->              ngf-design="'.pdf,.jpg,video/*,!.jog'"              <!--  comma separated wildcard to filter file names and                                            types allowed you can exclude specific files by ! at the beginning. validate mistake proper noun: blueprint -->              ngf-min-size,              ngf-max-size,              ngf-max-total-size="100"              in              bytes              or              "'10KB'" or "'10MB'" or "'10GB'"              <!--  validate as form.file.$error.maxSize=true and file.$error='maxSize'                              ngf-max-total-size is for multiple file select and validating the total size of all files. -->              ngf-min-height, ngf-max-height, ngf-min-width, ngf-max-width="g"              in              pixels              only              images              <!--  validate error names: minHeight, maxHeight, minWidth, maxWidth -->              ngf-ratio="8:x,ane.6"              <!--  list of comma separated valid aspect ratio of images in float or 2:iii format                              validate mistake proper name: ratio -->              ngf-min-ratio,              ngf-max-ratio="8:x"              <!--  min or max allowed aspect ratio for the paradigm. -->              ngf-dimensions="$width > grand || $height > k"              or              "validateDimension($file, $width, $height)"              <!--  validate the epitome dimensions, validate fault name: dimensions -->              ngf-min-elapsing, ngf-max-duration="100.5"              in              seconds              or              "'10s'" or "'10m'" or "'10h'" only sound, video              <!--  validate error name: maxDuration -->              ngf-elapsing="$duration > 1000"              or              "validateDuration($file, $duration)"              <!--  validate the media duration, validate fault name: duration -->              ngf-validate="{size: {min: x, max: '20MB'}, width: {min: 100, max:10000}, height: {min: 100, max: 300}                              ratio: '2x1', elapsing: {min: '10s', max: '5m'}, design: '.jpg'}"              <!-- shorthand form for to a higher place validations in ane place. -->              ngf-validate-fn="validate($file)"              <!--  custom validation office, return boolean or string                                            containing the error. validate error name: validateFn -->              ngf-validate-async-fn="validate($file)"              <!--  custom validation function, render a promise that                                            resolve to boolean or cord containing the mistake. validate error name: validateAsyncFn -->              ngf-validate-strength="boolean"              <!--  default false, if true file.$mistake volition be prepare if                                            the dimension or duration values for validations cannot be calculated for example                                            epitome load error or unsupported video by the browser. by default it would assume the file                                            is valid if the duration or dimension cannot be calculated by the browser. -->              ngf-ignore-invalid="'blueprint maxSize'"              <!--  ignore the files that fail the specified validations.                                            They will just be ignored and will not show upward in ngf-model-invalid or make the course invalid.                              space separated list of validate mistake names. -->              ngf-run-all-validations="boolean"              <!--  default false. Runs all the specified validate directives.                                            By default in one case a validation fails for a file it would end running other validations for that file. -->              >Upload/Drop</              div              >              <              div              |...              ngf-no-file-drop              >File Drag/drop is not supported</              div              >              <!--  filter to convert the file to base64 data url. -->              <              a              href="file | ngfDataUrl">epitome</              a              >            

File preview

              <              img              |audio|video|div              *ngf-src="file"              <!-- To preview the selected file, sets src attribute to the file information url. -->              *ngf-groundwork="file"              <!-- sets groundwork-image style to the file data url. -->              ngf-resize="{width: 20, meridian: 20, quality: 0.nine}"              <!--  only for image resizes the paradigm                                            before setting it equally src or groundwork image. quality is optional. -->              ngf-no-object-url="true or simulated"              <!--  run into #887 to force base64 url generation instead of                                            object url. Default imitation -->              >              <              div              |span|...              *ngf-thumbnail="file"              <!-- Generates a thumbnail version of the image file -->              ngf-size="{width: 20, summit: xx, quality: 0.ix}"              the              prototype              will              exist              resized              to              this              size              <!--  if not specified will exist resized to this element`s customer width and elevation. -->              ngf-equally-groundwork="boolean"              <!-- if true it will set up the background paradigm way instead of src attribute. -->              >            

Upload service:

              var              upload              =              Upload              .              upload              (              {              *              url:              'server/upload/url'              ,              // upload.php script, node.js route, or servlet url              /*                              Specify the file and optional data to be sent to the server.                              Each field including nested objects volition be sent as a form data multipart.                              Samples: {pic: file, username: username}                              {files: files, otherInfo: {id: id, person: person,...}} multiple files (html5)                              {profiles: {[{pic: file1, username: username1}, {pic: file2, username: username2}]} nested array multiple files (html5)                              {file: file, info: Upload.json({id: id, proper name: name, ...})} ship fields equally json string                              {file: file, info: Upload.jsonBlob({id: id, proper name: name, ...})} send fields as json blob, 'application/json' content_type                              {picFile: Upload.rename(file, 'contour.jpg'), title: title} transport file with picFile cardinal and contour.jpg file name*/              *              data:              {              key:              file              ,              otherInfo:              uploadInfo              }              ,              /*                              This is to accommodate server implementations expecting nested data object keys in .cardinal or [key] format.                              Instance: data: {rec: {proper noun: 'N', motion picture: file}} sent as: rec[name] -> N, rec[pic] -> file                              data: {rec: {name: 'Northward', motion picture: file}}, objectKey: '.chiliad' sent every bit: rec.proper name -> N, rec.pic -> file */              objectKey:              '[thou]'              or              '.k'              // default is '[thousand]'              /*                              This is to adapt server implementations expecting array data object keys in '[i]' or '[]' or                              ''(multiple entries with same fundamental) format.                              Example: data: {rec: [file[0], file[ane], ...]} sent equally: rec[0] -> file[0], rec[ane] -> file[i],...                              data: {rec: {rec: [f[0], f[1], ...], arrayKey: '[]'} sent as: rec[] -> f[0], rec[] -> f[1],...*/              arrayKey:              '[i]'              or              '[]'              or              '.i'              or              ''              //default is '[i]'              method:              'Mail'              or              'PUT'              (              html5              )              ,              default              Mail service              ,              headers:              {              'Authorization':              '30'              }              ,              // only for html5              withCredentials:              boolean              ,              /*                              See resumable upload guide beneath the code for more details (html5 simply) */              resumeSizeUrl:              '/uploaded/size/url?file='              +              file              .              name              // uploaded file size and then far on the server.              resumeSizeResponseReader:              function              (              data              )              {              render              information              .              size              ;              }              // reads the uploaded file size from resumeSizeUrl Go response              resumeSize:              part              (              )              {              return              promise              ;              }              // office that returns a prommise which will exist              // resolved to the upload file size on the server.              resumeChunkSize:              10000              or              '10KB'              or              '10MB'              // upload in chunks of specified size              disableProgress:              boolean              // default faux, experimental as hotfix for potential library conflicts with other plugins              .              .              .              and              all              other              angular              $http              (              )              options              could              be              used              here              .              }              )              // returns a promise              upload              .              and then              (              function              (              resp              )              {              // file is uploaded successfully              console              .              log              (              'file '              +              resp              .              config              .              data              .              file              .              name              +              'is uploaded successfully. Response: '              +              resp              .              information              )              ;              }              ,              role              (              resp              )              {              // handle fault              }              ,              function              (              evt              )              {              // progress notify              console              .              log              (              'progress: '              +              parseInt              (              100.0              *              evt              .              loaded              /              evt              .              total              )              +              '% file :'              +              evt              .              config              .              data              .              file              .              proper name              )              ;              }              )              ;              upload              .              grab              (              errorCallback              )              ;              upload              .              finally              (              callback              ,              notifyCallback              )              ;              /* access or attach event listeners to the underlying XMLHttpRequest */              upload              .              xhr              (              function              (              xhr              )              {              xhr              .              upload              .              addEventListener              (...)              }              )              ;              /* cancel/abort the upload in progress. */              upload              .              abort              (              )              ;              /*              alternative way of uploading, send the file binary with the file's content-type.              Could be used to upload files to CouchDB, imgur, etc... html5 FileReader is needed.              This is equivalent to angular $http() but allow you lot to listen to the progress outcome for HTML5 browsers.*/              Upload              .              http              (              {              url:              '/server/upload/url'              ,              headers              :              {              'Content-Type':              file              .              type              }              ,              data:              file              }              )              /* Set the default values for ngf-select and ngf-drop directives*/              Upload              .              setDefaults              (              {              ngfMinSize:              20000              ,              ngfMaxSize:20000000              ,              ...}              )              // These two defaults could be decreased if y'all experience out of memory problems              // or could be increased if your app needs to prove many images on the page.              // Each prototype in ngf-src, ngf-background or ngf-thumbnail is stored and referenced as a hulk url              // and will merely be released if the max value of the followings is reached.              Upload              .              defaults              .              blobUrlsMaxMemory              =              268435456              // default max total size of files stored in hulk urls.              Upload              .              defaults              .              blobUrlsMaxQueueSize              =              200              // default max number of hulk urls stored by this application.              /* Convert a single file or array of files to a single or array of              base64 information url representation of the file(southward).              Could be used to send file in base64 format within json to the databases */              Upload              .              base64DataUrl              (              files              )              .              and so              (              function              (              urls              )              {...}              )              ;              /* Catechumen the file to blob url object or base64 data url based on boolean disallowObjectUrl value */              Upload              .              dataUrl              (              file              ,              boolean              )              .              then              (              office              (              url              )              {...}              )              ;              /* Get prototype file dimensions*/              Upload              .              imageDimensions              (              file              )              .              and so              (              office              (              dimensions              )              {              console              .              log              (              dimensions              .              width              ,              dimensions              .              summit              )              ;              }              )              ;              /* Get audio/video duration*/              Upload              .              mediaDuration              (              file              )              .              and so              (              part              (              durationInSeconds              )              {...}              )              ;              /* Resizes an prototype. Returns a promise */              // options: width, elevation, quality, type, ratio, centerCrop, resizeIf, restoreExif              //resizeIf(width, height) returns boolean. See ngf-resize directive for more than details of options.              Upload              .              resize              (              file              ,              options              )              .              so              (              function              (              resizedFile              )              {...}              )              ;              /* returns boolean showing if epitome resize is supported by this browser*/              Upload              .              isResizeSupported              (              )              /* returns boolean showing if resumable upload is supported by this browser*/              Upload              .              isResumeSupported              (              )              /* returns a file which will be uploaded with the newName instead of original file proper name */              Upload              .              rename              (              file              ,              newName              )              /* converts the object to a Blob object with awarding/json content type              for jsob byte streaming support #359 (html5 only)*/              Upload              .              jsonBlob              (              obj              )              /* converts the value to json to send data every bit json string. Same as angular.toJson(obj) */              Upload              .              json              (              obj              )              /* converts a dataUrl to Blob object.*/              var              blob              =              upload              .              dataUrltoBlob              (              dataurl              ,              name              )              ;              /* returns true if there is an upload in progress. Tin be used to prompt user earlier endmost browser tab */              Upload              .              isUploadInProgress              (              )                            boolean              /* downloads and converts a given url to Blob object which could be added to files model */              Upload              .              urlToBlob              (              url              )              .              then              (              function              (              hulk              )              {...}              )              ;              /* returns boolean to bank check if the object is file and could be used as file in Upload.upload()/http() */              Upload              .              isFile              (              obj              )              ;              /* fixes the exif orientation of the jpeg image file*/              Upload              .              applyExifRotation              (              file              )              .              and so              (...)            

ng-model The model value will be a unmarried file instead of an array if all of the followings are truthful:

  • ngf-multiple is not set up or is resolved to false.
  • multiple attribute is not set on the element
  • ngf-keep is not fix or is resolved to false.

validation When whatever of the validation directives specified the form validation will take place and you tin access the value of the validation using myForm.myFileInputName.$mistake.<validate mistake proper name> for example class.file.$mistake.pattern. If multiple file choice is allowed you can specify ngf-model-invalid="invalidFiles" to assing the invalid files to a model and observe the error of each individual file with file.$error and description of information technology with file.$errorParam. Y'all tin use athwart ngf-model-options to allow invalid files to be set to the ng-model ngf-model-options="{allowInvalid: true}".

Upload multiple files: Only for HTML5 FormData browsers (not IE8-9) you have an array of files or more than one file in your information to send them all in one request . Non-html5 browsers due to flash limitation will upload each file one by one in a divide request. You should iterate over the files and send them one past one for a cantankerous browser solution.

drag and drop styling: For file elevate and driblet, ngf-drag-over-class could be used to style the drop zone. Information technology can be a function that returns a class name based on the $effect. Default is "dragover" string. Only in chrome Information technology could exist a json object {take: 'a', 'reject': 'r', blueprint: 'image/*', filibuster: 10} that specify the class name for the accepted or rejected drag overs. The pattern specified or ngf-blueprint will be used to validate the file's mime-type since that is the but property of the file that is reported by the browser on drag. Then you cannot validate 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. filibuster default is 100, and is used to ready css3 transition bug from dragging over/out/over #277.

Upload.setDefaults(): If you have many file selects or drops yous can set the default values for the directives by calling Upload.setDefaults(options). options would exist a json object with directive names in camelcase and their default values.

Resumable Uploads: The plugin supports resumable uploads for large files. On your server you lot need to keep track of what files are being uploaded and how much of the file is uploaded.

  • 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.
  • resumeSizeUrl server endpoint to return uploaded file size and so far on the server to be able to resume the upload from where it is ended. It should render naught if the file has not been uploaded even so.
    A Get request volition be made to that url for each upload to make up one's mind if office of the file is already uploaded or non. You demand a unique way of identifying the file on the server and so y'all can laissez passer the file name or generated id for the file as a asking parameter.
    By default it will assume that the response content is an integer or a json object with size integer property. If you return other formats from the endpoint you lot tin can specify resumeSizeResponseReader function to render the size value from the response. Alternatively instead of resumeSizeUrl you can use resumeSize function which returns a promise that resolves to the size of the uploaded file so far. Make sure when the file is fully uploaded without any fault/arrest this endpoint returns zilch for the file size if you want to allow the user to upload the aforementioned file once again. Or optionally you could have a restart endpoint to set that back to zippo to permit re-uploading the same file.
  • resumeChunkSize optionally yous can specify this to upload the file in chunks to the server. This volition let uploading to GAE or other servers that have file size limitation and trying to upload the whole request before passing information technology for internal processing.
    If this option is set the requests will accept the post-obit extra fields: _chunkSize, _currentChunkSize, _chunkNumber (zero starting), and _totalSize to aid the server to write the uploaded chunk to the correct position. Uploading in chunks could slow downwardly the overall upload time particularly if the chunk size is too pocket-size. When you provide resumeChunkSize option i of the resumeSizeUrl or resumeSize is mandatory to know how much of the file is uploaded then far.

Old browsers

For browsers not supporting HTML5 FormData (IE8, IE9, ...) FileAPI module is used. Note: Y'all demand Flash installed on your browser since FileAPI uses Wink to upload files.

These two files FileAPI.min.js, FileAPI.flash.swf will be loaded past the module on need (no demand to exist 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              >              //optional need to be loaded before angular-file-upload-shim(.min).js              FileAPI              =              {              //only one of jsPath or jsUrl.              jsPath:              '/js/FileAPI.min.js/folder/'              ,              jsUrl:              'yourcdn.com/js/FileAPI.min.js'              ,              //only one of staticPath or flashUrl.              staticPath:              '/wink/FileAPI.flash.swf/folder/'              ,              flashUrl:              'yourcdn.com/js/FileAPI.wink.swf'              ,              //forceLoad: true, html5: faux //to debug flash in HTML5 browsers              //noContentTimeout: 10000 (see #528)              }              </              script              >              <              script              src="angular-file-upload-shim.min.js">              </              script              >...

Old browsers known issues:

  • Considering of a Flash limitation/problems if the server doesn't send any response body the status code of the response will be e'er 204 'No Content'. So if y'all take admission to your server upload lawmaking at least return a character in the response for the condition lawmaking to work properly.
  • Custom headers will not work due to a Flash limitation #111 #224 #129
  • Due to Flash bug #92 Server HTTP fault lawmaking 400 volition 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 instance of an mistake response (http code >= 400) the custom error message returned from the server may not be available. For some error codes flash merely provide a generic error message and ignores the response text. #310
  • Older browsers won't allow PUT requests. #261

Server Side

  • Java You can find the sample server lawmaking in Java/GAE hither
  • Spring MVC Wiki Sample provided by zouroto
  • Node.js Wiki Sample provided by chovy. Some other wiki using Express 4.0 and the Multiparty provided by Jonathan White
  • Rails
    • Wiki Sample provided by guptapriyank.
    • Blog mail provided by Coshx Labs.
    • Runway progress event: If your server is Track and Apache you may need to modify server configurations for the server to back up upload progress. Run into #207
  • PHP Wiki Sample and related issue simply i file in $_FILES when uploading multiple files
  • .Net
    • Demo showing how to use ng-file-upload with Asp.Cyberspace Web Api.
    • Sample customer and server code demo/C# provided by AtomStar

CORS

To back up CORS upload your server needs to allow cross domain requests. You lot can achieve that by having a filter or interceptor on your upload file server to add CORS headers to the response like to this: (sample java code)

httpResp.setHeader(                "Access-Command-Permit-Methods"              ,                              "POST, PUT, OPTIONS"              ); httpResp.setHeader(                "Access-Control-Allow-Origin"              ,                              "your.other.server.com"              ); httpResp.setHeader(                "Access-Command-Allow-Headers"              ,                              "Content-Type"              ));

For non-HTML5 IE8-9 browsers you would also demand a crossdomain.xml file at the root of your server to allow CORS for flash: (sample xml)

<cross-domain-policy>   <site-command              permitted-cross-domain-policies=                "all"              />   <allow-admission-from              domain=                "angular-file-upload.appspot.com"              />   <let-http-request-headers-from              domain=                "*"                            headers=                "*"                            secure=                "false"              /> </cross-domain-policy>

Amazon AWS S3 Upload

For Amazon authentication version iv see this comment

The demo folio has an selection to upload to S3. Here is a sample config options:

              Upload              .              upload              (              {              url:              'https://angular-file-upload.s3.amazonaws.com/'              ,              //S3 upload url including saucepan proper noun              method:              'Postal service'              ,              data:              {              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 saucepan: private, public-read, ...         policy: $telescopic.policy, // base64-encoded json policy (see article below)         signature: $scope.signature, // base64-encoded signature based on policy string (see article below)         "Content-Blazon": file.type != '' ? file.type : 'application/octet-stream', // content blazon of the file (NotEmpty)         filename: file.name, // this is needed for Flash polyfill IE8-9         file: file              }              }              )              ;            

This article explains more than about these fields and provides instructions on how to generate the policy and signature using a server side tool. These two values are generated from the json policy document which looks similar this:

              {              "expiration":              "2020-01-01T00:00:00Z"              ,              "conditions":              [              {              "saucepan":              "angular-file-upload"              }              ,              [              "starts-with"              ,              "$primal"              ,              ""              ]              ,              {              "acl":              "private"              }              ,              [              "starts-with"              ,              "$Content-Type"              ,              ""              ]              ,              [              "starts-with"              ,              "$filename"              ,              ""              ]              ,              [              "content-length-range"              ,              0              ,              524288000              ]              ]              }            

The demo folio provide a helper tool to generate the policy and signature from you lot from the json policy certificate. Notation: Please use https protocol to access demo page if you are using this tool to generate signature and policy to protect your aws underground key which should never be shared.

Make sure that you provide upload and CORS post to your saucepan at AWS -> S3 -> bucket name -> Properties -> Edit saucepan policy and Edit CORS Configuration. Samples of these ii files:

              {              "Version":              "2012-10-17"              ,              "Argument":              [              {              "Sid":              "UploadFile"              ,              "Effect":              "Let"              ,              "Principal":              {              "AWS":              "arn:aws:iam::xxxx:user/xxx"              }              ,              "Action":              [              "s3:GetObject"              ,              "s3:PutObject"              ]              ,              "Resource":              "arn:aws:s3:::athwart-file-upload/*"              }              ,              {              "Sid":              "crossdomainAccess"              ,              "Effect":              "Allow"              ,              "Principal":              "*"              ,              "Action":              "s3:GetObject"              ,              "Resources":              "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-ix flash polyfill you lot need to accept a crossdomain.xml file at the root of y'all S3 bucket. Make sure the content-type of crossdomain.xml is text/xml and y'all provide read access to this file in your bucket policy.

You tin also have a await at https://github.com/nukulb/s3-athwart-file-upload for some other example with this gear up.

Source: https://github.com/danialfarid/ng-file-upload

Posted by: bryantlosigiand.blogspot.com

0 Response to "How Upload Files To Github"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel