FileAPI — a set of javascript tools for working with files. Multiupload, drag'n'drop and chunked file upload. Images: crop, resize and auto orientation by EXIF.
A set of JavaScript tools for working with files.
Download the files from the dist directory, and then:
Choose files<script>window.FileAPI = { staticPath: '/js/FileAPI/dist/' };</script> <script src="/js/FileAPI/dist/FileAPI.min.js"></script> <script> var choose = document.getElementById('choose'); FileAPI.event.on(choose, 'change', function (evt){ var files = FileAPI.getFiles(evt); // Retrieve file list FileAPI.filterFiles(files, function (file, info/**Object*/){ if( /^image/.test(file.type) ){ return info.width >= 320 && info.height >= 240; } return false; }, function (files/**Array*/, rejected/**Array*/){ if( files.length ){ // Make preview 100x100 FileAPI.each(files, function (file){ FileAPI.Image(file).preview(100).get(function (err, img){ images.appendChild(img); }); }); // Uploading Files FileAPI.upload({ url: './ctrl.php', files: { images: files }, progress: function (evt){ /* ... */ }, complete: function (err, xhr){ /* ... */ } }); } }); }); </script>
Edit the file
crossdomain.xmland place it to the root of the domain to which files will be uploaded.
<!-- OR --> <script> window.FileAPI = { /* options */ }; require(['FileAPI'], function (FileAPI){ // ... }); </script>
:HTMLInputElement|Event|$.Event)
:Array
Retrieve file list from
inputelement or
eventobject, also support
jQuery.
HTMLInputElement,
changeand
dropevent,
jQuerycollection or
jQuery.Event
var el = document.getElement('my-input'); FileAPI.event.on(el, 'change', function (evt/**Event*/){ // Retrieve file list var files = FileAPI.getFiles(el);// or event var files = FileAPI.getFiles(evt);
});
:Object, callback
:Function)
:void
Get info of file (see also: FileAPI.addInfoReader).
// Get info of image file (FileAPI.exif.js included) FileAPI.getInfo(file, function (err/**String*/, info/**Object*/){ if( !err ){ console.log(info); // { width: 800, height: 600, exif: {..} } } });// Get info of mp3 file (FileAPI.id3.js included) FileAPI.getInfo(file, function (err/*String/, info/*Object/){ if( !err ){ console.log(info); // { title: "...", album: "...", artists: "...", ... } } });
:Array, filter
:Function, callback
:Function)
:void
Filtering the list of files, with additional information about files. See also: FileAPI.getInfo and FileAPI.addInfoReader.
file— the file itself,
info— additional information.
list— files that match the condition,
other— all the rest.
// Get list of file var files = FileAPI.getFiles(input);// Filter the List FileAPI.filterFiles(files, function (file/*Object/, info/*Object/){ if( /^image/.test(file.type) && info ){ return info.width > 320 && info.height > 240; } else { return file.size < 20 * FileAPI.MB; } }, function (list/*Array/, other/*Array/){ if( list.length ){ // .. } });
:Event|$.Event, callback
:Function)
:void
Get a list of files, including directories.
dropevent
FileAPI.event.on(document, 'drop', function (evt/**Event*/){ evt.preventDefault();// Get a list of files FileAPI.getDropFiles(evt, function (files/**Array*/){ // ... });
});
:Object)
:XmlHttpRequest
Uploading 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".
var el = document.getElementById('my-input'); FileAPI.event.on(el, 'change', function (evt/**Event*/){ var files = FileAPI.getFiles(evt); var xhr = FileAPI.upload({ url: 'http://rubaxa.org/FileAPI/server/ctrl.php', files: { file: files[0] }, complete: function (err, xhr){ if( !err ){ var result = xhr.responseText; // ... } } }); });
:RegExp, handler
:Function)
:void
Adds a handler for the collection of information about a file. See also: FileAPI.getInfo and FileAPI.filterFiles.
fileobject and
completefunction callback
FileAPI.addInfoReader(/^image/, function (file/**File*/, callback/**Function*/){ // http://www.nihilogic.dk/labs/exif/exif.js // http://www.nihilogic.dk/labs/binaryajax/binaryajax.js FileAPI.readAsBinaryString(file, function (evt/**Object*/){ if( evt.type == 'load' ){ var binaryString = evt.result; var oFile = new BinaryFile(binaryString, 0, file.size); var exif = EXIF.readFromBinaryFile(oFile); callback(false, { 'exif': exif || {} }); } else if( evt.type == 'error' ){ callback('read_as_binary_string'); } else if( evt.type == 'progress' ){ // ... } }); });
:Object, callback
:Function)
:void
Reading the contents of the specified
Fileas
dataURL.
FileAPI.readAsDataURL(file, function (evt/**Object*/){ if( evt.type == 'load' ){ // Success var dataURL = evt.result; } else if( evt.type =='progress' ){ var pr = evt.loaded/evt.total * 100; } else { // Error } })
:Object, callback
:Function)
:void
Reading the contents of the specified
Fileas
BinaryString.
FileAPI.readAsBinaryString(file, function (evt/**Object*/){ if( evt.type == 'load' ){ // Success var binaryString = evt.result; } else if( evt.type =='progress' ){ var pr = evt.loaded/evt.total * 100; } else { // Error } })
:Object, callback
:Function)
:void
Reading the contents of the specified
Fileas
ArrayBuffer.
FileAPI.readAsArrayBuffer(file, function (evt/**Object*/){ if( evt.type == 'load' ){ // Success var arrayBuffer = evt.result; } else if( evt.type =='progress' ){ var pr = evt.loaded/evt.total * 100; } else { // Error } })
:Object, callback
:Function)
:void
Reading the contents of the specified
Fileas
text.
FileAPI.readAsText(file, function (evt/**Object*/){ if( evt.type == 'load' ){ // Success var text = evt.result; } else if( evt.type =='progress' ){ var pr = evt.loaded/evt.total * 100; } else { // Error } })
:Object, encoding
:String, callback
:Function)
:void
Reading the contents of the specified
Fileas
text.
FileAPI.readAsText(file, "utf-8", function (evt/**Object*/){ if( evt.type == 'load' ){ // Success var text = evt.result; } else if( evt.type =='progress' ){ var pr = evt.loaded/evt.total * 100; } else { // Error } })
:String
A string containing the URL to which the request is sent.
:Object
Additional post data to be sent along with the file uploads.
var xhr = FileAPI.upload({ url: '...', data: { 'session-id': 123 }, files: { ... }, });
:String
Request method, HTML5 only.
var xhr = FileAPI.upload({ url: '...', uploadMethod: 'PUT', files: { .. }, });
:Boolean
Pass credentials to upload request, HTML5 only.
var xhr = FileAPI.upload({ url: '...', uploadCredentials: false, files: { .. }, });
:Object
Additional request headers, HTML5 only.
var xhr = FileAPI.upload({ url: '...', headers: { 'x-upload': 'fileapi' }, files: { .. }, });
:Boolean
Setting to true removes the default timestamp URL parameter.
:Object
Key-value object,
key— post name,
value— File or FileAPI.Image object.
var xhr = FileAPI.upload({ url: '...', files: { audio: files } });
:Number
Chunk size in bytes, HTML5 only.
var xhr = FileAPI.upload({ url: '...', files: { images: fileList }, chunkSize: 0.5 * FileAPI.MB });
:Number
Number of retries during upload chunks, HTML5 only.
var xhr = FileAPI.upload({ url: '...', files: { images: fileList }, chunkSize: 0.5 * FileAPI.MB, chunkUploadRetry: 3 });
--
:Object
Rules of changes the original image on the client.
var xhr = FileAPI.upload({ url: '...', files: { image: imageFiles }, // Changes the original image imageTransform: { // resize by max side maxWidth: 800, maxHeight: 600, // Add watermark overlay: [{ x: 10, y: 10, src: '/i/watemark.png', rel: FileAPI.Image.RIGHT_BOTTOM }] } });
--
:Object
Rules of image transformation on the client, for more images.
var xhr = FileAPI.upload({ url: '...', files: { image: imageFiles }, imageTransform: { // resize by max side 'huge': { maxWidth: 800, maxHeight: 600 }, // crop & resize 'medium': { width: 320, height: 240, preview: true }, // crop & resize + watemark 'small': { width: 100, height: 100, // Add watermark overlay: [{ x: 5, y: 5, src: '/i/watemark.png', rel: FileAPI.Image.RIGHT_BOTTOM }] } } });
--
:Object
Convert all images to jpeg or png.
var xhr = FileAPI.upload({ url: '...', files: { image: imageFiles }, imageTransform: { type: 'image/jpeg', quality: 0.86 // jpeg quality } });
:Boolean
Sent to the server the original image or not, if defined imageTransform option.
--
:Boolean
Auto-rotate images on the basis of EXIF.
--
:Function
Prepare options upload for a particular file.
var xhr = FileAPI.upload({ url: '...', files: { .. } prepare: function (file/**Object*/, options/**Object*/){ options.data.secret = utils.getSecretKey(file.name); } });
--
:Function
Start uploading.
var xhr = FileAPI.upload({ url: '...', files: { .. } upload: function (xhr/**Object*/, options/**Object*/){ // ... } });
--
:Function
Start file uploading.
var xhr = FileAPI.upload({ url: '...', files: { .. } fileupload: function (file/**Object*/, xhr/**Object*/, options/**Object*/){ // ... } });
--
:Function
Callback for upload progress events.
var xhr = FileAPI.upload({ url: '...', files: { .. } progress: function (evt/**Object*/, file/**Object*/, xhr/**Object*/, options/**Object*/){ var pr = evt.loaded/evt.total * 100; } });
--
:Function
Callback for upload file progress events.
var xhr = FileAPI.upload({ url: '...', files: { .. } fileprogress: function (evt/**Object*/, file/**Object*/, xhr/**Object*/, options/**Object*/){ var pr = evt.loaded/evt.total * 100; } });
--
:Function
Callback for end upload requests.
var xhr = FileAPI.upload({ url: '...', files: { .. } complete: function (err/**String*/, xhr/**Object*/, file/**Object/, options/**Object*/){ if( !err ){ // All files successfully uploaded. } } });
--
:Function
Callback for end upload requests.
var xhr = FileAPI.upload({ url: '...', files: { .. } filecomplete: function (err/**String*/, xhr/**Object*/, file/**Object/, options/**Object*/){ if( !err ){ // File successfully uploaded var result = xhr.responseText; } } });
The name of the file referenced by the File object.
The type (MIME type) of the file referenced by the File object.
The size (in bytes) of the file referenced by the File object.
:HTMLElement, events
:String, handler
:Function)
:void
Attach an event handler function.
:HTMLElement, events
:String, handler
:Function)
:void
Remove an event handler.
:HTMLElement, events
:String, handler
:Function)
:void
Attach an event handler function. The handler is executed at most once.
:HTMLElement, hover
:Function, handler
:Function)
:void
Attach an drag and drop event handler function.
dragenterand
dragleavelistener
dropevent handler.
var el = document.getElementById('dropzone'); FileAPI.event.dnd(el, function (over){ el.style.backgroundColor = over ? '#f60': ''; }, function (files){ if( files.length ){ // Upload their. } });// or jQuery $('#dropzone').dnd(hoverFn, dropFn);
:HTMLElement, hover
:Function, handler
:Function)
:void
Remove an drag and drop event handler function.
dragenterand
dragleavelistener
dropevent handler.
// Native FileAPI.event.dnd.off(el, hoverFn, dropFn);// jQuery $('#dropzone').dndoff(hoverFn, dropFn);
--
Class for working with images
:Object)
:void
The constructor takes a single argument, the
Fileobject.
Fileobject
FileAPI.Image(imageFile).get(function (err/**String*/, img/**HTMLElement*/){ if( !err ){ document.body.appendChild( img ); } });
:Number, height
:Number)
:FileAPI.Image
Crop image by width and height.
FileAPI.Image(imageFile) .crop(640, 480) .get(function (err/**String*/, img/**HTMLElement*/){})
;
:Number, y
:Number, width
:Number, height
:Number)
:FileAPI.Image
Crop image by x, y, width and height.
FileAPI.Image(imageFile) .crop(100, 50, 320, 240) .get(function (err/**String*/, img/**HTMLElement*/){})
;
:Number, height
:Number[, strategy
:String])
:FileAPI.Image
Resize image.
min,
max,
preview,
width,
height. By default
undefined.
FileAPI.Image(imageFile) .resize(320, 240) .get(function (err/**String*/, img/**HTMLElement*/){})
;
// Resize image on by max side. FileAPI.Image(imageFile) .resize(320, 240, 'max') .get(function (err/*String/, img/*HTMLElement/){
})
;
// Resize image on by fixed height. FileAPI.Image(imageFile) .resize(240, 'height') .get(function (err/*String/, img/*HTMLElement/){
})
;
:Number[, height
:Number])
:FileAPI.Image
Crop and resize image.
FileAPI.Image(imageFile) .preview(100, 100) .get(function (err/**String*/, img/**HTMLElement*/){})
;
:Number)
:FileAPI.Image
Rotate image.
FileAPI.Image(imageFile) .rotate(90) .get(function (err/**String*/, img/**HTMLElement*/){})
;
:Function)
:FileAPI.Image
Apply filter function. Only
HTML5.
canvaselement and
donemethod.
FileAPI.Image(imageFile) .filter(function (canvas/**HTMLCanvasElement*/, doneFn/**Function*/){ // bla-bla-lba doneFn(); }) .get(function (err/**String*/, img/**HTMLElement*/){})
;
:String)
:FileAPI.Image
Uses CamanJS, include it before FileAPI library.
Caman.Filter.register("my-funky-filter", function () { // http://camanjs.com/guides/#Extending });FileAPI.Image(imageFile) .filter("my-funky-filter") // or .filter("vintage") .get(function (err/*String/, img/*HTMLElement/){
})
;
:Array)
:FileAPI.Image
Add overlay images, eg: watermark.
FileAPI.Image(imageFile) .overlay([ // Left corner. { x: 10, y: 10, w: 100, h: 10, src: '/i/watermark.png' },// Right bottom corner. { x: 10, y: 10, src: '/i/watermark.png', rel: FileAPI.Image.RIGHT_BOTTOM } ]) .get(function (err/**String*/, img/**HTMLElement*/){ })
;
:Function)
:FileAPI.Image
Get the final image.
To work with a webcam, be sure to set
FileAPI.media: true.
:HTMLElement, options
:Object, callback
:Function)
:void
Publication of the camera.
width: 100%,
height: 100%,
start: true}
var el = document.getElementById('cam'); FileAPI.Camera.publish(el, { width: 320, height: 240 }, function (err, cam/**FileAPI.Camera*/){ if( !err ){ // The webcam is ready, you can use it. } });
:Function)
:void
Turn on the camera.
var el = document.getElementById('cam'); FileAPI.Camera.publish(el, { start: false }, function (err, cam/**FileAPI.Camera*/){ if( !err ){ // Turn on cam.start(function (err){ if( !err ){ // The camera is ready for use. } }); } });
:void
Turn off the camera.
:FileAPI.Image
Take a picture with the camera.
var el = document.getElementById('cam'); FileAPI.Camera.publish(el, function (err, cam/**FileAPI.Camera*/){ if( !err ){ var shot = cam.shot(); // take a picture// create thumbnail 100x100 shot.preview(100).get(function (err, img){ previews.appendChild(img); }); // and/or FileAPI.upload({ url: '...', files: { cam: shot }); }
});
:Number
1024 bytes
:Number
1048576 bytes
:Number
1073741824 bytes
:Number
1.0995116e+12 bytes
:Object|Array, callback
:Function[, thisObject
:Mixed])
:void
Iterate over an object or array, executing a function for each matched element.
thiswhen executing
callback.
--
:Object, src
:Object)
:Object
Merge the contents of two objects together into the first object.
--
:Array, callback
:Function[, thisObject
:Mixed)
:Object
Creates a new array with all elements that pass the test implemented by the provided function.
thiswhen executing
callback.
:Boolean
HTML5 browser support
:Boolean
This cross-origin resource sharing is used to enable cross-site HTTP requests.
:Boolean
Drag'n'drop events support.
:Boolean
Availability Flash plugin.
:Boolean
Canvas support.
:Boolean
Support dataURI as src for image.
:Boolean
Support chunked upload.
Flash is very "buggy" thing :] The server response can not be empty. Therefore, in the event of a successful uploading
http statusshould be only
200 OK.
Flash settings. It is advisable to place flash on the same server where the files will be uploaded.
Necessarily make this file on the server. Do not forget to replace
youdomain.comon the name of your domain.
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.1 Accept: text/* Content-Type: multipart/form-data; boundary=----------Ij5ae0ae0KM7GI3KM7 User-Agent: Shockwave Flash Host: www.youdomain.com Content-Length: 421 Connection: Keep-Alive Cache-Control: no-cache------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7 Content-Disposition: form-data; name="Filename"
MyFile.jpg ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7 Content-Disposition: form-data; name="Filedata"; filename="MyFile.jpg" Content-Type: application/octet-stream
[[..FILE_DATA_HERE..]] ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7 Content-Disposition: form-data; name="Upload"
Submit Query ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7--
By default
FileAPI.flash.swfallows 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.
FileAPI::OK , 'statusText' => 'OK' , 'body' => array('count' => sizeof($files)) ), $jsonp); exit; } ?>
Enable CORS.
Client and server communicate to each other using the following HTTP headers and status codes.
Client explicitly sets the following headers:
chunkUploadRetrytimes then fails.
All the other codes - fatal error, user's involvement is recommended.
Simple input[type="file"]
Stylized button.
Upload files
Button like link.
Upload photo
npm install fileapi
cd fileapi
npm install
grunt