A set of JavaScript tools for working with files.
Get started
Download the files from the dist directory, and then:
<!-- "js-fileapi-wrapper" -- required class --> Choose files <!-- previews -->
Setup options
Edit the file crossdomain.xml
and place it to the root of the domain to which files will be uploaded.
<!-- OR -->
:HTMLInputElement|Event|$.Event
):Array
getFiles(inputRetrieve file list from input
element or event
object, also support jQuery
.
- input —
HTMLInputElement
,change
anddrop
event,jQuery
collection orjQuery.Event
var el = document;FileAPIevent;
:Object
, callback:Function
):void
getInfo(fileGet info of file (see also: FileAPI.addInfoReader).
- file — file object (https://developer.mozilla.org/en-US/docs/DOM/File)
- callback — function, called after collected info of file
// Get info of image file (FileAPI.exif.js included)FileAPI; // Get info of mp3 file (FileAPI.id3.js included)FileAPI;
:Array
, filter:Function
, callback:Function
):void
filterFiles(filesFiltering the list of files, with additional information about files. See also: FileAPI.getInfo and FileAPI.addInfoReader.
- files — original list of files
- filter — function, takes two arguments:
file
— the file itself,info
— additional information. - callback — function:
list
— files that match the condition,other
— all the rest.
// Get list of filevar files = FileAPI; // Filter the ListFileAPI;
:Event|$.Event
, callback:Function
):void
getDropFiles(evtGet a list of files, including directories.
- evt —
drop
event - callback — function, takes one argument, a list of files
FileAPIevent;
:Object
):XmlHttpRequest
upload(optsUploading files to the server (successively). Returns XHR-like object. It is important to remember to correctly worked flash-transport server response body must not be empty, for example, you can pass, just text "ok".
- opts — options object, see Upload options
var el = document;FileAPIevent;
:RegExp
, handler:Function
):void
addInfoReader(mimeAdds a handler for the collection of information about a file. See also: FileAPI.getInfo and FileAPI.filterFiles.
- mime — pattern of mime-type
- handler — takes two arguments:
file
object andcomplete
function callback
FileAPI;
:Object
, callback:Function
):void
readAsDataURL(fileReading the contents of the specified File
as dataURL
.
- file — file object
- callback — function, receives a result
FileAPI
:Object
, callback:Function
):void
readAsBinaryString(fileReading the contents of the specified File
as BinaryString
.
- file — file object
- callback — function, receives a result
FileAPI
:Object
, callback:Function
):void
readAsArrayBuffer(fileReading the contents of the specified File
as ArrayBuffer
.
- file — file object
- callback — function, receives a result
FileAPI
:Object
, callback:Function
):void
readAsText(fileReading the contents of the specified File
as text
.
- file — file object
- callback — function, receives a result
FileAPI
:Object
, encoding:String
, callback:Function
):void
readAsText(fileReading the contents of the specified File
as text
.
- encoding — a string indicating the encoding to use for the returned data. By default, UTF-8.
FileAPI
Upload options
:String
urlA string containing the URL to which the request is sent.
:Object
dataAdditional post data to be sent along with the file uploads.
var xhr = FileAPI;
:String
uploadMethodRequest method, HTML5 only.
var xhr = FileAPI;
:Boolean
uploadCredentialsPass credentials to upload request, HTML5 only.
var xhr = FileAPI;
:Object
headersAdditional request headers, HTML5 only.
var xhr = FileAPI;
:Boolean
cacheSetting to true removes the default timestamp URL parameter.
:Object
filesKey-value object, key
— post name, value
— File or FileAPI.Image object.
var xhr = FileAPI;
:Number
chunkSizeChunk size in bytes, HTML5 only.
var xhr = FileAPI;
:Number
chunkUploadRetryNumber of retries during upload chunks, HTML5 only.
var xhr = FileAPI;
--
:Object
imageTransformRules of changes the original image on the client.
var xhr = FileAPI;
--
:Object
imageTransformRules of image transformation on the client, for more images.
var xhr = FileAPI;
--
:Object
imageTransformConvert all images to jpeg or png.
var xhr = FileAPI;
:Boolean
imageOriginalSent to the server the original image or not, if defined imageTransform option.
--
:Boolean
imageAutoOrientationAuto-rotate images on the basis of EXIF.
--
:Function
preparePrepare options upload for a particular file.
var xhr = FileAPI;
--
:Function
uploadStart uploading.
var xhr = FileAPI;
--
:Function
fileuploadStart file uploading.
var xhr = FileAPI;
--
:Function
progressCallback for upload progress events.
var xhr = FileAPI;
--
:Function
fileprogressCallback for upload file progress events.
var xhr = FileAPI;
--
:Function
completeCallback for end upload requests.
var xhr = FileAPI;
--
:Function
filecompleteCallback for end upload requests.
var xhr = FileAPI;
File object
name
The name of the file referenced by the File object.
type
The type (MIME type) of the file referenced by the File object.
size
The size (in bytes) of the file referenced by the File object.
FileAPI.event
:HTMLElement
, events:String
, handler:Function
):void
on(elAttach an event handler function.
- el — DOM element
- events — one or more space-separated event types.
- handler — A function to execute when the event is triggered.
:HTMLElement
, events:String
, handler:Function
):void
off(elRemove an event handler.
- el — DOM element
- events — one or more space-separated event types.
- handler — a handler function previously attached for the event(s).
:HTMLElement
, events:String
, handler:Function
):void
one(elAttach an event handler function. The handler is executed at most once.
- el — DOM element
- events — one or more space-separated event types.
- handler — a function to execute when the event is triggered.
:HTMLElement
, hover:Function
, handler:Function
):void
dnd(elAttach an drag and drop event handler function.
- el — drop zone
- hover —
dragenter
anddragleave
listener - handler —
drop
event handler.
var el = document;FileAPIevent; // or jQuery;
:HTMLElement
, hover:Function
, handler:Function
):void
dnd.off(elRemove an drag and drop event handler function.
- el — drop zone
- hover —
dragenter
anddragleave
listener - handler —
drop
event handler.
// NativeFileAPIeventdnd; // jQuery;
--
FileAPI.Image
Class for working with images
:Object
):void
constructor(fileThe constructor takes a single argument, the File
object.
- file — the
File
object
FileAPI;
:Number
, height:Number
):FileAPI.Image
crop(widthCrop image by width and height.
- width — new image width
- height — new image height
FileAPI ;
:Number
, y:Number
, width:Number
, height:Number
):FileAPI.Image
crop(xCrop image by x, y, width and height.
- x — offset from the top corner
- y — offset from the left corner
FileAPI ;
:Number
, height:Number
[, strategy:String
]):FileAPI.Image
resize(widthResize image.
- width — new image width
- height — new image height
- strategy — enum:
min
,max
,preview
,width
,height
. By defaultundefined
.
FileAPI ; // Resize image on by max side.FileAPI ; // Resize image on by fixed height.FileAPI ;
:Number
[, height:Number
]):FileAPI.Image
preview(widthCrop and resize image.
- width — new image width
- height — new image height
FileAPI ;
:Number
):FileAPI.Image
rotate(degRotate image.
- deg — rotation angle in degrees
FileAPI ;
:Function
):FileAPI.Image
filter(callbackApply filter function. Only HTML5
.
- callback — takes two arguments,
canvas
element anddone
method.
FileAPI ;
:String
):FileAPI.Image
filter(nameUses CamanJS, include it before FileAPI library.
- name — CamanJS filter name (custom or preset)
CamanFilter; FileAPI // or .filter("vintage") ;
:Array
):FileAPI.Image
overlay(imagesAdd overlay images, eg: watermark.
- images — array of overlays
FileAPI ;
:Function
):FileAPI.Image
get(fnGet the final image.
- fn — complete callback
FileAPI.Camera
To work with a webcam, be sure to set FileAPI.media: true
.
:HTMLElement
, options:Object
, callback:Function
):void
publish(elPublication of the camera.
- el — target
- options — {
width: 100%
,height: 100%
,start: true
} - callback — the first parameter is a possible error, the second instance of FileAPI.Camera
var el = document;FileAPICamera;
:Function
):void
start(callbackTurn on the camera.
- callback — will be called when the camera ready
var el = document;FileAPICamera;
:void
stop()Turn off the camera.
:FileAPI.Image
shot()Take a picture with the camera.
var el = document;FileAPICamera
Constants
:Number
FileAPI.KB1024 bytes
:Number
FileAPI.MB1048576 bytes
:Number
FileAPI.GB1073741824 bytes
:Number
FileAPI.TB1.0995116e+12 bytes
Utils
:Object|Array
, callback:Function
[, thisObject:Mixed
]):void
FileAPI.each(objIterate over an object or array, executing a function for each matched element.
- obj — array or object
- callback — a function to execute for each element.
- thisObject — object to use as
this
when executingcallback
.
--
:Object
, src:Object
):Object
FileAPI.extend(dstMerge the contents of two objects together into the first object.
- dst — an object that will receive the new properties
- src — an object containing additional properties to merge in.
--
:Array
, callback:Function
[, thisObject:Mixed
):Object
FileAPI.filter(arrayCreates a new array with all elements that pass the test implemented by the provided function.
- array — original Array
- callback — Function to test each element of the array.
- thisObject — object to use as
this
when executingcallback
.
Support
- Multiupload: all browsers that support HTML5 or Flash
- Drag'n'Drop upload: files (HTML5) & directories (Chrome 21+)
- Chunked file upload (HTML5)
- Upload one file: all browsers
-
Working with Images: IE6+, FF 3.6+, Chrome 10+, Opera 11.1+, Safari 6+
- crop, resize, preview & rotate (HTML5 or Flash)
- auto orientation by exif (HTML5, if include FileAPI.exif.js or Flash)
:Boolean
FileAPI.support.html5HTML5 browser support
:Boolean
FileAPI.support.corsThis cross-origin resource sharing is used to enable cross-site HTTP requests.
:Boolean
FileAPI.support.dndDrag'n'drop events support.
:Boolean
FileAPI.support.flashAvailability Flash plugin.
:Boolean
FileAPI.support.canvasCanvas support.
:Boolean
FileAPI.support.dataURISupport dataURI as src for image.
:Boolean
FileAPI.support.chunkedSupport chunked upload.
Flash
Flash is very "buggy" thing :]
The server response can not be empty.
Therefore, in the event of a successful uploading http status
should be only 200 OK
.
Settings
Flash settings. It is advisable to place flash on the same server where the files will be uploaded.
crossdomain.xml
Necessarily make this file on the server.
Do not forget to replace youdomain.com
on the name of your domain.
request
The following sample HTTP POST request is sent from Flash Player to a server-side script if no parameters are specified:
POST /server/ctrl.php HTTP/1.1Accept: text/*Content-Type: multipart/form-data;boundary=----------Ij5ae0ae0KM7GI3KM7User-Agent: Shockwave FlashHost: www.youdomain.comContent-Length: 421Connection: Keep-AliveCache-Control: no-cache ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7Content-Disposition: form-data; name="Filename" MyFile.jpg------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7Content-Disposition: form-data; name="Filedata"; filename="MyFile.jpg"Content-Type: application/octet-stream [[..FILE_DATA_HERE..]]------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7Content-Disposition: form-data; name="Upload" Submit Query------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7--
Security
By default FileAPI.flash.swf
allows access from any domain via Security.allowDomain("*")
.
This can lead to same origin bypass vulnerability if swf is loaded from the same domain as your critical data.
To prevent this, allow only your domains here and rebuild flash.
Server settings
IFrame/JSONP
<!-- or -->
CORS
Enable CORS.
Chunked file upload
Client and server communicate to each other using the following HTTP headers and status codes.
Client explicitly sets the following headers:
- Content-Range: bytes <start-offset>-<end-offset>/<total>
- Content-Disposition: attachment; filename=<file-name>
Response codes:
- 200 - last chunk is uploaded
- 201 - chunk is successfully saved
- 416 - range is not acceptable error, recoverable
- 500 - server error, recoverable
Buttons examples
Base
Simple input[type="file"]
Button
Stylized button.
Upload files
Link
Button like link.
Upload photo
Installation, testing, assembling
npm install fileapi
cd fileapi
npm install
grunt
Changelog
2.0.20
- #369: * IEMobile
2.0.19
- #367: * [flash] allow gif and bmp to resize
2.0.18
- #364: * Camera#stop
- #363: * support `Blob` in `FileAPI.getInfo`
- #361: + upload zero-files
2.0.16-2.0.17
- #353: debug mode vs. IE
- #352: correct filename via flash-uploading
2.0.12-2.0.15 (!)
- #346, #342, #344: fixes for XSS into Flash-transport
2.0.11
- #322, #308: dnd & safari + $.fn.dnd (store all dropped items)
- #319: NodeJS tesing
- #317, #313: fixed "malformed entry.name (OSX Unicode NFD)"
- #311: fixed "Arithmetic result exceeded 32 bits"
2.0.10
- #289: * WebCam & html5 == false
- #199, #265: flash fix 2015 error with BitmapData
- #177: IE9, IE11 flash.camera remembered settigns
- #254: check 'onLoadFnName' before call
- #272: fixed `entry.createReader().readEntries`
2.0.9
- #253: fixed `proxyXHR.loaded`
- #250: + check `disabled`-attr
2.0.8
- Two new resize strategies `width` and `height`
2.0.7
- #214: iframe transport under IE8
- Fixed iframe-transport (remove `disabled`-attr for input)
2.0.6
- #240: Fixed `FileAPI.event.dnd.off`
2.0.5
- + #228: check callbacks with regexp
- * Updated devDepending
- + #207: support EXIF.Orientation == 4, 5 & 7
2.0.4
- + #176: Add params to the beginning of form
- + #190: Add 204 as a successful response
- + #192: many bugfixes; + `retry` & `multipass` options; + QUnit-tests for BigSizeImage
2.0.3
- + QUnit-tests for iframe-transport
- + `postMessage` for iframe-transport
- + `jsonp: "callback"` option
- * resize: `imageTransform.type` rename to `imageTransform.strategy` (!!!)
- + https://github.com/mailru/FileAPI/pull/165 (#140: fix)
2.0.2
- + test: upload headers
- + test: upload + camanjs
- + test: upload + autoOrientation
- FileAPI.class.php: + HTTP header Content-Type: application/json
- #143: + `FileAPI.flashWebcamUrl` option
- * merge v1.2.7
- + `FileAPI.formData: true` option
2.0.1
- + support 'filter' prop in imageTransform
2.0.0
- + FileAPI.Camera (HTML5 and Flash fallback)
- + jquery.fileapi.js, see demo
- + npm support
- + grunt support
- + requirejs support
- + [#80](https://https://github.com/mailru/FileAPI/issues/80): FileAPI.Image.fn.overlay
- `imageTransform` — now supports: `crop`, `type`, `quality` and `overlay` properties.
- Improved the documentation
- +iOS fix (https://github.com/blueimp/JavaScript-Load-Image)
- [#121](https://github.com/mailru/FileAPI/issues/121): + FileAPI.`postNameConcat:Function(name, idx)`
- [#116](https://github.com/mailru/FileAPI/issues/116): + `cache:false` option for FileAPI.upload
1.2.6
- [#91](https://github.com/mailru/FileAPI/issues/91): replace `new Image` to `FileAPI.newImage`
- + FileAPI.withCredentials: true
- [#90](https://github.com/mailru/FileAPI/issues/90): Fixed `progress` event
- [#105](https://github.com/mailru/FileAPI/issues/105): Fixed `image/jpg` -> `image/jpeg`
- [#108](https://github.com/mailru/FileAPI/issues/108): Check width/height before resize by type(min/max)
1.2.5
- [#86](https://github.com/mailru/FileAPI/issues/86): Smarter upload recovery
- [#87](https://github.com/mailru/FileAPI/issues/87): Fixed upload files into browsers that do not support FormData
- Fixed support "accept" attribute for Flash.
- Fixed detection of HTML5 support for FireFox 3.6
- + FileAPI.html5 option, default "true"
1.2.4
- Fixed auto orientation image by EXIF (Flash)
- Fixed image dimensions after rotate (Flash)
- [#82](https://github.com/mailru/FileAPI/issues/82): "undefined" data-fields cause exceptions
- [#83](https://github.com/mailru/FileAPI/issues/83): Allow requests without files
- [#84](https://github.com/mailru/FileAPI/pull/84): Fixed connection abort when waiting for connection recovery
1.2.3
- [#77](https://github.com/mailru/FileAPI/pull/77): Fixed flash.abort(), [#75](https://github.com/mailru/FileAPI/issues/75)
- - `FileAPI.addMime`
- + `FileAPI.accept` — fallback for flash.
1.2.2
- [#67](https://github.com/mailru/FileAPI/pull/67): Added correct httpStatus for upload fail, [#62](https://github.com/mailru/FileAPI/pull/68)
- [#68](https://github.com/mailru/FileAPI/pull/68) Added "Content-Type" for chunked upload, [#65](https://github.com/mailru/FileAPI/pull/65)
- [#69](https://github.com/mailru/FileAPI/issues/69): Fixed network down recovery
- Fixed progress event, [#66](https://github.com/mailru/FileAPI/issues/66)
- Increase flash stage size, [#73](https://github.com/mailru/FileAPI/pull/73)
- - array index from POST-param "name", [#72](https://github.com/mailru/FileAPI/issues/72)
- - dependency on FileAPI.Image for FileAPI.Flash
1.2.1
- [#64](https://github.com/mailru/FileAPI/issues/64): Bufixed for [#63](https://github.com/mailru/FileAPI/issues/63)
1.2.0
- [#57](https://github.com/mailru/FileAPI/issues/57): Chunked file upload
1.1.0
- [#54](https://github.com/mailru/FileAPI/issues/54): added `FileAPI.flashUrl` and `FileAPI.flashImageUrl`
1.0.1
- [#51](https://github.com/mailru/FileAPI/issues/51): remove circular references from `file-objects` (Flash transport)
- added `changelog`
1.0.0
- first release