File Upload Restrict to Camera and Not Gallery Using Angularjs
ng-file-upload
Lightweight Angular directive to upload files.
See the DEMO page. Reference docs here
Migration notes: version iii.0.x version three.one.ten version iii.2.ten version iv.10.x version v.x.x version 6.x.x version 6.2.x version vii.0.x version 7.two.x version 8.0.x version nine.0.x version 10.0.x version xi.0.x version 12.0.x version 12.i.x version 12.ii.ten
Enquire questions on StackOverflow under the ng-file-upload tag.
For problems written report or feature request delight search through existing problems first and then open a new one hither. For faster response provide steps to reproduce/versions with a jsfiddle link. If yous need back up for your company contact me.
If you similar this plugin give it a thumbs upwards at ngmodules or go me a loving cup of tea . Contributions are welcomed.
Table of Content:
- Features
- Install (Transmission, Bower, NuGet, NPM)
- Usage
- One-time Browsers
- Server Side
- Samples (Java, Bound, Node.js, Rails, PHP, .Net)
- CORS
- Amazon S3 Upload
Features
- file upload progress, cancel/abort
- file elevate and drib (html5 merely)
- image paste from clipboard and drag and drib from browser pages (html5 only).
- prototype resize and centre ingather (native) and user controlled crop through ngImgCrop. See crop sample (html5 only)
- orientation fix for jpeg paradigm files with exif orientation information
- resumable uploads: break/resume upload (html5 just)
- native validation support for file type/size, image width/superlative/aspect ratio, video/audio duration, and
ng-required
with pluggable custom sync or async validations. - show thumbnail or preview of selected images/sound/videos
- supports CORS and direct upload of file's binary data using
Upload.$http()
- enough of sample server side lawmaking, available on nuget
- on need flash FileAPI shim loading no actress load for html5 browsers.
- HTML5 FileReader.readAsDataURL shim for IE8-9
- available on npm, bower, meteor, nuget
Install
- Manual: download latest from here
- Bower:
-
bower install ng-file-upload-shim --save
(for non html5 suppport) -
bower install ng-file-upload --relieve
-
- NuGet:
PM> Install-Package athwart-file-upload
(cheers to Georgios Diamantopoulos) - NPM:
npm install ng-file-upload
< script src="athwart(.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 form submit and validations: http://jsfiddle.net/danialfarid/maqbzv15/1118/
- Upload multiple files one by one on file select: http://jsfiddle.net/danialfarid/2vq88rfs/136/
- Upload multiple files in one request on file select (html5 only): http://jsfiddle.internet/danialfarid/huhjo9jm/v/
- Upload single file on file select: http://jsfiddle.cyberspace/danialfarid/0mz6ff9o/135/
- Drop and upload with $watch: http://jsfiddle.cyberspace/danialfarid/s8kc7wg0/400/
- Image Crop and Upload http://jsfiddle.internet/danialfarid/xxo3sk41/590/
< script src="athwart.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 push click < form ng-app="fileUpload" ng-controller="MyCtrl" name="form"> 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-height="100" ngf-resize="{width: 100, height: 100}">Select</ div > Multiple files < div class="button" ngf-select ng-model="files" ngf-multiple="true">Select</ div > Driblet files: < div ngf-drop ng-model="files" class="drop-box">Drop</ div > < button type="submit" ng-click="submit()">submit</ button > </ form > Upload right abroad after file selection: < div class="button" ngf-select="upload($file)">Upload on file select</ div > < div class="button" ngf-select="uploadFiles($files)" multiple="multiple">Upload on file select</ div > Drop File: < div ngf-drib="uploadFiles($files)" course="driblet-box" ngf-drag-over-class="'dragover'" ngf-multiple="true" ngf-design="'image/*,awarding/pdf'">Drib Images or PDFs files hither</ div > < div ngf-no-file-drop >File Drag/Driblet is not supported for this browser</ div > Prototype thumbnail: < img ngf-thumbnail="file || '/pollex.jpg'"> Audio preview: < audio controls ngf-src="file"> </ audio > Video preview: < video controls ngf-src="file"> </ video >
Javascript lawmaking:
//inject directives and services. var app = angular . module ( 'fileUpload' , [ 'ngFileUpload' ] ) ; app . controller ( 'MyCtrl' , [ '$telescopic' , 'Upload' , office ( $scope , Upload ) { // upload later on form submit or something similar $scope . submit = role ( ) { if ( $scope . course . file . $valid && $scope . file ) { $scope . upload ( $telescopic . file ) ; } } ; // upload on file select or drop $telescopic . upload = function ( file ) { Upload . upload ( { url: 'upload/url' , data: { file: file , 'username': $scope . username } } ) . then ( part ( resp ) { console . log ( 'Success ' + resp . config . data . file . name + 'uploaded. Response: ' + resp . information ) ; } , function ( resp ) { console . log ( 'Error condition: ' + resp . condition ) ; } , function ( evt ) { var progressPercentage = parseInt ( 100.0 * evt . loaded / evt . total ) ; panel . log ( 'progress: ' + progressPercentage + '% ' + evt . config . data . file . name ) ; } ) ; } ; // for multiple files: $scope . uploadFiles = office ( 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 ( {..., information: { file: files } , ...} ) . . . ; } } } ] ) ;
Full reference
File select and drib
At least one of the ngf-select
or ngf-driblet
are mandatory for the plugin to link to the element. ngf-select
only attributes are marked with * and ngf-drib
merely attributes are marked with +.
< div |button|input type="file"|ngf-select|ngf-drib... ngf-select="" or "upload($files, ...)" <!-- chosen when files are selected or cleared --> ngf-drop="" or "upload($files, ...)" <!-- called when files existence dropped You tin utilise ng-model or ngf-change instead of specifying function for ngf-drib and ngf-select function parameters are the same equally ngf-modify --> ngf-change="upload($files, $file, $newFiles, $duplicateFiles, $invalidFiles, $event)" <!-- called when files are selected, dropped, or cleared --> ng-model="myFiles" <!-- binds the valid selected/dropped file or files to the telescopic model could be an assortment or single file depending on ngf-multiple and ngf-keep values. --> ngf-model-options="{updateOn: 'change click drop dropUrl paste', allowInvalid: fake, debounce: 0}" <!-- updateOn could be used to disable resetting on click, or updating on paste, browser epitome driblet, etc. allowInvalid default is false could permit invalid files in the model debouncing volition postpone model update (miliseconds). See athwart ng-model-options for more details. --> ngf-model-invalid="invalidFile(south)" <!-- binds the invalid selected/dropped file or files to this model. --> ngf-before-model-alter="beforeChange($files, ...)" <!-- called afterward file select/drop and before model alter, validation and resize is processed --> ng-disabled="boolean" <!-- disables this element --> ngf-select-disabled="boolean" <!-- default false, disables file select on this element --> ngf-drop-disabled="boolean" <!-- default simulated, disables file driblet on this element --> ngf-multiple="boolean" <!-- default false, allows selecting multiple files --> ngf-keep="true|false|'distinct'" <!-- default false, go along the previous ng-model files and append the new files. "'distinct'" removes duplicate files $newFiles and $duplicateFiles are fix in ngf-change/select/driblet functions. --> ngf-set up-orientation="boolean" <!-- default false, would rotate the jpeg image files that have exif orientation data. Come across #745. Could exist a boolean office similar shouldFixOrientation($file) to make up one's mind wethere to set that file or not. --> *ngf-capture="'camera'" or "'other'" <!-- allows mobile devices to capture using camera --> *ngf-take="'image/*'" <!-- standard HTML accept attr, browser specific select popup window --> +ngf-allow-dir="boolean" <!-- default true, allow dropping files only for Chrome webkit browser --> +ngf-include-dir="boolean" <!-- default imitation, include directories in the dropped file array. You tin observe if they are directory or not by checking the type === 'directory'. --> +ngf-elevate-over-form="{pattern: 'image/*', accept:'acceptClass', reject:'rejectClass', filibuster:100}" or "'myDragOverClass'" or "calcDragOverClass($upshot)" <!-- default "dragover". drag over css class behaviour. could be a string, a function returning class proper name or a json object. accept/turn down course only works in Chrome, validating only the file mime type. if design is not specified ngf-design will be used. See following docs for more info. --> +ngf-drag="drag($isDragging, $class, $event)" <!-- role chosen on drag over/leave events. $isDragging: boolean true if is dragging over(dragover), fake if drag has left (dragleave) $grade is the form that is being gear up for the chemical element calculated by ngf-drag-over-class --> +ngf-drib-available="dropSupported" <!-- prepare the value of scope model to truthful or false based on file drag&drop back up for this browser --> +ngf-terminate-propagation="boolean" <!-- default false, whether to propagate elevate/drop events. --> +ngf-hibernate-on-drop-non-available="boolean" <!-- default imitation, hides element if file drag&drop is not --> +ngf-enable-firefox-paste="boolean" <!-- *experimental* default false, enable firefox image paste by making element contenteditable --> ngf-resize="{width: 100, meridian: 100, quality: .eight, type: 'image/jpeg', ratio: '1:ii', centerCrop: true, pattern='.jpg', restoreExif: false}" or resizeOptions() <!-- a function returning a promise which resolves into the options. resizes the paradigm to the given width/top or ratio. Quality is optional between 0.ane and 1.0), type is optional convert it to the given image type format. centerCrop true will center crop the image if it does not fit inside the given width/meridian or ratio. centerCrop imitation (default) will not crop the image and will fit it within the given width/pinnacle or ratio and so the resulting image width (or height) could exist less than given width (or top). blueprint is to resize only the files that their name or type matches the design similar to ngf-pattern. restoreExif boolean default true, will restore exif info on the resized image. --> ngf-resize-if="$width > 1000 || $height > 1000" or "resizeCondition($file, $width, $height)" <!-- utilize ngf-resize only if this function returns true. To filter specific images to be resized. --> ngf-validate-afterwards-resize="boolean" <!-- default false, if true all validation will exist run later the images are being resized, so any validation error before resize will be ignored. --> <!-- validations: --> ngf-max-files="ten" <!-- maximum number of files allowed to be selected or dropped, validate error name: maxFiles --> ngf-pattern="'.pdf,.jpg,video/*,!.jog'" <!-- comma separated wildcard to filter file names and types allowed you can exclude specific files past ! at the beginning. validate error name: pattern --> ngf-min-size, ngf-max-size, ngf-max-total-size="100" in bytes or "'10KB'" or "'10MB'" or "'10GB'" <!-- validate as form.file.$mistake.maxSize=truthful and file.$error='maxSize' ngf-max-total-size is for multiple file select and validating the total size of all files. --> ngf-min-peak, ngf-max-height, ngf-min-width, ngf-max-width="1000" in pixels just images <!-- validate error names: minHeight, maxHeight, minWidth, maxWidth --> ngf-ratio="8:10,i.half-dozen" <!-- list of comma separated valid aspect ratio of images in bladder or 2:3 format validate error name: ratio --> ngf-min-ratio, ngf-max-ratio="8:10" <!-- min or max allowed aspect ratio for the epitome. --> ngf-dimensions="$width > yard || $meridian > g" or "validateDimension($file, $width, $top)" <!-- validate the image dimensions, validate error proper noun: dimensions --> ngf-min-elapsing, ngf-max-duration="100.five" in seconds or "'10s'" or "'10m'" or "'10h'" only audio, video <!-- validate mistake name: maxDuration --> ngf-duration="$duration > thousand" or "validateDuration($file, $duration)" <!-- validate the media duration, validate error proper noun: duration --> ngf-validate="{size: {min: x, max: '20MB'}, width: {min: 100, max:10000}, height: {min: 100, max: 300} ratio: '2x1', duration: {min: '10s', max: '5m'}, pattern: '.jpg'}" <!-- shorthand course for in a higher place validations in one place. --> ngf-validate-fn="validate($file)" <!-- custom validation function, return boolean or string containing the fault. validate fault proper noun: validateFn --> ngf-validate-async-fn="validate($file)" <!-- custom validation function, return a promise that resolve to boolean or cord containing the error. validate error name: validateAsyncFn --> ngf-validate-force="boolean" <!-- default false, if true file.$error will exist set if the dimension or duration values for validations cannot be calculated for example image load error or unsupported video by the browser. by default it would presume the file is valid if the duration or dimension cannot exist calculated by the browser. --> ngf-ignore-invalid="'pattern maxSize'" <!-- ignore the files that fail the specified validations. They volition simply be ignored and will not show upward in ngf-model-invalid or make the form invalid. space separated list of validate error names. --> ngf-run-all-validations="boolean" <!-- default faux. Runs all the specified validate directives. By default once a validation fails for a file it would cease running other validations for that file. --> >Upload/Drop</ div > < div |... ngf-no-file-drop >File Elevate/drop is not supported</ div > <!-- filter to convert the file to base64 data url. --> < a href="file | ngfDataUrl">epitome</ a >
File preview
< img |sound|video|div *ngf-src="file" <!-- To preview the selected file, sets src attribute to the file data url. --> *ngf-groundwork="file" <!-- sets background-image style to the file data url. --> ngf-resize="{width: 20, height: 20, quality: 0.9}" <!-- just for epitome resizes the image before setting information technology every bit src or background image. quality is optional. --> ngf-no-object-url="true or faux" <!-- see #887 to force base64 url generation instead of object url. Default false --> > < div |span|... *ngf-thumbnail="file" <!-- Generates a thumbnail version of the image file --> ngf-size="{width: twenty, height: 20, quality: 0.9}" the image will exist resized to this size <!-- if not specified will be resized to this element`due south client width and elevation. --> ngf-every bit-background="boolean" <!-- if true information technology volition set the background image manner instead of src attribute. --> >
Upload service:
var upload = Upload . upload ( { * url: 'server/upload/url' , // upload.php script, node.js road, or servlet url /* Specify the file and optional data to exist sent to the server. Each field including nested objects will exist sent as a form information multipart. Samples: {pic: file, username: username} {files: files, otherInfo: {id: id, person: person,...}} multiple files (html5) {profiles: {[{pic: file1, username: username1}, {motion-picture show: file2, username: username2}]} nested assortment multiple files (html5) {file: file, info: Upload.json({id: id, name: proper name, ...})} send fields as json string {file: file, info: Upload.jsonBlob({id: id, proper name: proper name, ...})} send fields equally json blob, 'awarding/json' content_type {picFile: Upload.rename(file, 'profile.jpg'), title: title} transport file with picFile central and contour.jpg file name*/ * data: { primal: file , otherInfo: uploadInfo } , /* This is to accommodate server implementations expecting nested information object keys in .key or [key] format. Example: information: {rec: {proper noun: 'North', motion-picture show: file}} sent equally: rec[name] -> N, rec[pic] -> file data: {rec: {name: 'N', pic: file}}, objectKey: '.k' sent as: rec.proper noun -> N, rec.picture show -> file */ objectKey: '[1000]' or '.k' // default is '[g]' /* This is to accommodate server implementations expecting array data object keys in '[i]' or '[]' or ''(multiple entries with same key) format. Example: data: {rec: [file[0], file[i], ...]} sent every bit: rec[0] -> file[0], rec[1] -> file[1],... data: {rec: {rec: [f[0], f[1], ...], arrayKey: '[]'} sent every bit: rec[] -> f[0], rec[] -> f[1],...*/ arrayKey: '[i]' or '[]' or '.i' or '' //default is '[i]' method: 'Mail' or 'PUT' ( html5 ) , default POST , headers: { 'Authorization': 'xxx' } , // only for html5 withCredentials: boolean , /* See resumable upload guide beneath the code for more details (html5 only) */ resumeSizeUrl: '/uploaded/size/url?file=' + file . proper name // uploaded file size and then far on the server. resumeSizeResponseReader: function ( data ) { return information . size ; } // reads the uploaded file size from resumeSizeUrl GET response resumeSize: function ( ) { return hope ; } // function that returns a prommise which will be // resolved to the upload file size on the server. resumeChunkSize: 10000 or '10KB' or '10MB' // upload in chunks of specified size disableProgress: boolean // default simulated, experimental as hotfix for potential library conflicts with other plugins . . . and all other angular $http ( ) options could be used here . } ) // returns a promise upload . then ( part ( resp ) { // file is uploaded successfully panel . log ( 'file ' + resp . config . data . file . name + 'is uploaded successfully. Response: ' + resp . information ) ; } , office ( resp ) { // handle error } , function ( evt ) { // progress notify console . log ( 'progress: ' + parseInt ( 100.0 * evt . loaded / evt . full ) + '% file :' + evt . config . data . file . name ) ; } ) ; upload . take hold of ( errorCallback ) ; upload . finally ( callback , notifyCallback ) ; /* access or attach outcome listeners to the underlying XMLHttpRequest */ upload . xhr ( office ( xhr ) { xhr . upload . addEventListener (...) } ) ; /* cancel/abort the upload in progress. */ upload . abort ( ) ; /* alternative way of uploading, transport the file binary with the file'south content-type. Could be used to upload files to CouchDB, imgur, etc... html5 FileReader is needed. This is equivalent to angular $http() but let you to listen to the progress issue 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 2 defaults could be decreased if you experience out of retentivity problems // or could be increased if your app needs to show many images on the page. // Each image in ngf-src, ngf-background or ngf-thumbnail is stored and referenced equally a hulk url // and will only be released if the max value of the followings is reached. Upload . defaults . blobUrlsMaxMemory = 268435456 // default max full size of files stored in blob urls. Upload . defaults . blobUrlsMaxQueueSize = 200 // default max number of blob urls stored by this application. /* Convert a single file or assortment of files to a single or array of base64 information url representation of the file(s). Could be used to transport file in base64 format within json to the databases */ Upload . base64DataUrl ( files ) . so ( function ( urls ) {...} ) ; /* Convert the file to blob url object or base64 data url based on boolean disallowObjectUrl value */ Upload . dataUrl ( file , boolean ) . then ( function ( url ) {...} ) ; /* Get image file dimensions*/ Upload . imageDimensions ( file ) . and then ( function ( dimensions ) { panel . log ( dimensions . width , dimensions . height ) ; } ) ; /* Get audio/video duration*/ Upload . mediaDuration ( file ) . then ( function ( durationInSeconds ) {...} ) ; /* Resizes an image. Returns a hope */ // options: width, acme, quality, type, ratio, centerCrop, resizeIf, restoreExif //resizeIf(width, peak) returns boolean. See ngf-resize directive for more details of options. Upload . resize ( file , options ) . then ( function ( resizedFile ) {...} ) ; /* returns boolean showing if prototype resize is supported past 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 name */ Upload . rename ( file , newName ) /* converts the object to a Blob object with application/json content type for jsob byte streaming support #359 (html5 only)*/ Upload . jsonBlob ( obj ) /* converts the value to json to send data as json string. Same as angular.toJson(obj) */ Upload . json ( obj ) /* converts a dataUrl to Blob object.*/ var hulk = upload . dataUrltoBlob ( dataurl , proper noun ) ; /* returns true if there is an upload in progress. Can exist used to prompt user before 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 ( role ( blob ) {...} ) ; /* returns boolean to 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 ) . then (...)
ng-model The model value will be a single file instead of an array if all of the followings are true:
-
ngf-multiple
is not set or is resolved to false. -
multiple
attribute is not set on the element -
ngf-keep
is non fix or is resolved to false.
validation When any of the validation directives specified the class validation will take place and you can access the value of the validation using myForm.myFileInputName.$fault.<validate fault name>
for example form.file.$error.pattern
. If multiple file selection is allowed you can specify ngf-model-invalid="invalidFiles"
to assing the invalid files to a model and find the fault of each private file with file.$error
and description of it with file.$errorParam
. Yous tin use angular 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 (non IE8-nine) you accept an array of files or more than one file in your data
to send them all in one request . Non-html5 browsers due to wink limitation will upload each file one by one in a separate asking. Yous should iterate over the files and send them i past one for a cross browser solution.
drag and drop styling: For file drag and drop, ngf-drag-over-grade
could be used to manner the driblet zone. Information technology tin be a role that returns a class name based on the $event. Default is "dragover" string. Merely in chrome It could exist a json object {take: 'a', 'reject': 'r', pattern: 'prototype/*', delay: 10}
that specify the class name for the accepted or rejected drag overs. The pattern
specified or ngf-pattern
will be used to validate the file's mime-blazon
since that is the merely property of the file that is reported by the browser on elevate. So you cannot validate the file proper noun/extension, size or other validations on elevate. There is also some limitation on some file types which are not reported by Chrome. delay
default is 100, and is used to fix css3 transition bug from dragging over/out/over #277.
Upload.setDefaults(): If you have many file selects or drops y'all tin can gear up 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.
Resumable Uploads: The plugin supports resumable uploads for large files. On your server you need to go along 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 so far on the server to be able to resume the upload from where it is ended. It should return zero if the file has not been uploaded yet.
A Get request volition be made to that url for each upload to determine if part of the file is already uploaded or non. Y'all need a unique manner of identifying the file on the server then y'all tin can pass the file name or generated id for the file as a request parameter.
By default it will assume that the response content is an integer or a json object withsize
integer belongings. If yous return other formats from the endpoint you can specifyresumeSizeResponseReader
function to return the size value from the response. Alternatively instead ofresumeSizeUrl
you lot can useresumeSize
function which returns a promise that resolves to the size of the uploaded file and so far. Make sure when the file is fully uploaded without any error/abort this endpoint returns zip for the file size if you lot want to allow the user to upload the aforementioned file over again. Or optionally you could have a restart endpoint to gear up that back to zero to allow re-uploading the same file. -
resumeChunkSize
optionally you tin specify this to upload the file in chunks to the server. This will let uploading to GAE or other servers that take file size limitation and trying to upload the whole request before passing information technology for internal processing.
If this option is prepare the requests volition take the following extra fields:_chunkSize
,_currentChunkSize
,_chunkNumber
(nothing starting), and_totalSize
to help the server to write the uploaded chunk to the correct position. Uploading in chunks could wearisome down the overall upload fourth dimension especially if the clamper size is besides small. When you provideresumeChunkSize
option 1 of theresumeSizeUrl
orresumeSize
is mandatory to know how much of the file is uploaded so far.
Old browsers
For browsers not supporting HTML5 FormData (IE8, IE9, ...) FileAPI module is used. Note: Yous need Flash installed on your browser since FileAPI
uses Flash to upload files.
These two files FileAPI.min.js
, FileAPI.wink.swf
volition 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 tin can place these ii 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 unlike path using the following script:
< script > //optional need to exist loaded before angular-file-upload-shim(.min).js FileAPI = { //only ane of jsPath or jsUrl. jsPath: '/js/FileAPI.min.js/folder/' , jsUrl: 'yourcdn.com/js/FileAPI.min.js' , //simply one of staticPath or flashUrl. staticPath: '/flash/FileAPI.flash.swf/binder/' , flashUrl: 'yourcdn.com/js/FileAPI.wink.swf' , //forceLoad: true, html5: false //to debug flash in HTML5 browsers //noContentTimeout: 10000 (see #528) } </ script > < script src="angular-file-upload-shim.min.js"> </ script >...
Old browsers known bug:
- Because of a Flash limitation/issues if the server doesn't transport any response torso the status code of the response will be e'er
204 'No Content'
. So if you have access to your server upload code at least return a graphic symbol in the response for the status code to work properly. - Custom headers volition not work due to a Wink limitation #111 #224 #129
- Due to Flash bug #92 Server HTTP error code 400 will be returned equally 200 to the client. So avoid returning 400 on your server side for upload response otherwise it will exist treated equally a success response on the client side.
- In instance of an error response (http code >= 400) the custom fault message returned from the server may non 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
- Java You can observe the sample server code in Coffee/GAE hither
- Spring MVC Wiki Sample provided by zouroto
- Node.js Wiki Sample provided by chovy. Another wiki using Limited 4.0 and the Multiparty provided by Jonathan White
- Runway
- Wiki Sample provided by guptapriyank.
- Blog mail service provided by Coshx Labs.
- Rail progress event: If your server is Rails and Apache y'all may need to modify server configurations for the server to back up upload progress. See #207
- PHP Wiki Sample and related effect but one file in $_FILES when uploading multiple files
- .Net
- Demo showing how to use ng-file-upload with Asp.Internet Spider web Api.
- Sample client and server lawmaking demo/C# provided by AtomStar
CORS
To back up CORS upload your server needs to allow cross domain requests. Y'all can accomplish that by having a filter or interceptor on your upload file server to add CORS headers to the response similar to this: (sample coffee code)
httpResp.setHeader("Access-Control-Allow-Methods", "Mail, PUT, OPTIONS"); httpResp.setHeader("Access-Control-Let-Origin", "your.other.server.com"); httpResp.setHeader("Admission-Command-Let-Headers", "Content-Type"));
For non-HTML5 IE8-9 browsers you would likewise need a crossdomain.xml
file at the root of your server to allow CORS for wink: (sample xml)
<cross-domain-policy> <site-control permitted-cross-domain-policies= "all" /> <permit-access-from domain= "athwart-file-upload.appspot.com" /> <allow-http-request-headers-from domain= "*" headers= "*" secure= "imitation" /> </cross-domain-policy>
Amazon AWS S3 Upload
For Amazon hallmark version four encounter this comment
The demo page has an option to upload to S3. Here is a sample config options:
Upload . upload ( { url: 'https://athwart-file-upload.s3.amazonaws.com/' , //S3 upload url including bucket name method: 'POST' , information: { fundamental: file . proper noun , // 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: individual, public-read, ... policy: $scope.policy, // base64-encoded json policy (come across article below) signature: $scope.signature, // base64-encoded signature based on policy string (see article below) "Content-Blazon": file.type != '' ? file.blazon : 'awarding/octet-stream', // content type of the file (NotEmpty) filename: file.proper name, // this is needed for Flash polyfill IE8-9 file: file } } ) ;
This article explains more than well-nigh 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" , "weather": [ { "saucepan": "angular-file-upload" } , [ "starts-with" , "$key" , "" ] , { "acl": "individual" } , [ "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 yous from the json policy document. Note: Delight use https protocol to access demo page if you are using this tool to generate signature and policy to protect your aws cloak-and-dagger key which should never exist shared.
Make sure that you provide upload and CORS postal service to your bucket at AWS -> S3 -> saucepan name -> Properties -> Edit bucket 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:::angular-file-upload/*" } , { "Sid": "crossdomainAccess" , "Upshot": "Permit" , "Principal": "*" , "Activeness": "s3:GetObject" , "Resource": "arn:aws:s3:::angular-file-upload/crossdomain.xml" } ] }
<?xml version= "1.0" encoding= "UTF-eight" ?> <CORSConfiguration xmlns= "http://s3.amazonaws.com/doc/2006-03-01/" > <CORSRule> <AllowedOrigin>http://athwart-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 lot S3 bucket. Make certain the content-type of crossdomain.xml is text/xml and you lot provide read access to this file in your saucepan policy.
You can too accept a look at https://github.com/nukulb/s3-angular-file-upload for another example with this fix.
Source: https://github.com/danialfarid/ng-file-upload
0 Response to "File Upload Restrict to Camera and Not Gallery Using Angularjs"
Postar um comentário