FileAPI
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.
Install / Use
/learn @mailru/FileAPIREADME
<a name="FileAPI"></a>
FileAPI <img src="https://api.travis-ci.org/mailru/FileAPI.png?branch=master"/>
A set of JavaScript tools for working with files.
<a name="started"></a>
Get started
Download the files from the dist directory, and then:
<div>
<!-- "js-fileapi-wrapper" -- required class -->
<div class="js-fileapi-wrapper upload-btn">
<div class="upload-btn__txt">Choose files</div>
<input id="choose" name="files" type="file" multiple />
</div>
<div id="images"><!-- previews --></div>
</div>
<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>
<a name="FileAPI.setup"></a>
Setup options
Edit the file crossdomain.xml and place it to the root of the domain to which files will be uploaded.
<script>
window.FileAPI = {
debug: false // debug mode, see Console
, cors: false // if used CORS, set `true`
, media: false // if used WebCam, set `true`
, staticPath: '/js/FileAPI/dist/' // path to '*.swf'
, postNameConcat: function (name, idx){
// Default: object[foo]=1&object[bar][baz]=2
// .NET: https://github.com/mailru/FileAPI/issues/121#issuecomment-24590395
return name + (idx != null ? '['+ idx +']' : '');
}
};
</script>
<script src="/js/FileAPI/dist/FileAPI.min.js"></script>
<!-- OR -->
<script>
window.FileAPI = { /* options */ };
require(['FileAPI'], function (FileAPI){
// ...
});
</script>
<a name="FileAPI.getFiles"></a>
getFiles(input:HTMLInputElement|Event|$.Event):Array
Retrieve file list from input element or event object, also support jQuery.
- input —
HTMLInputElement,changeanddropevent,jQuerycollection orjQuery.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);
});
<a name="FileAPI.getInfo"></a>
getInfo(file:Object, callback:Function):void
Get 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.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: "...", ... }
}
});
<a name="FileAPI.filterFiles"></a>
filterFiles(files:Array, filter:Function, callback:Function):void
Filtering 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 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 ){
// ..
}
});
<a name="FileAPI.getDropFiles"></a>
getDropFiles(evt:Event|$.Event, callback:Function):void
Get a list of files, including directories.
- evt —
dropevent - callback — function, takes one argument, a list of files
FileAPI.event.on(document, 'drop', function (evt/**Event*/){
evt.preventDefault();
// Get a list of files
FileAPI.getDropFiles(evt, function (files/**Array*/){
// ...
});
});
<a name="FileAPI.upload"></a>
upload(opts: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".
- opts — options object, see Upload options
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;
// ...
}
}
});
});
<a name="FileAPI.addInfoReader"></a>
addInfoReader(mime:RegExp, handler:Function):void
Adds 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:
fileobject andcompletefunction 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' ){
// ...
}
});
});
<a name="FileAPI.readAsDataURL"></a>
readAsDataURL(file:Object, callback:Function):void
Reading the contents of the specified File as dataURL.
- file — file object
- callback — function, receives a result
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
}
})
<a name="FileAPI.readAsBinaryString"></a>
readAsBinaryString(file:Object, callback:Function):void
Reading the contents of the specified File as BinaryString.
- file — file object
- callback — function, receives a result
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
}
})
<a name="FileAPI.readAsArrayBuffer"></a>
readAsArrayBuffer(file:Object, callback:Function):void
Reading the contents of the specified File as ArrayBuffer.
- file — file object
- callback — function, receives a result
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
}
})
<a name="FileAPI.readAsText"></a>
readAsText(file:Object, callback:Function):void
Reading the contents of the specified File as text.
- file — file object
- callback — function, receives a result
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
}
})
<a name="FileAPI.readAsText-encoding"></a>
readAsText(file:Object, encoding:String, callback:Function):void
Reading 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.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
}
})
<a name="options" data-name="Upload options"></a>
Upload options
<a name="options.url"></a>
url:String
A string containing the URL to which the request is sent.
<a name="options.data"></a>
data:Object
Additional post data to be sent along with the file uploads.
var xhr = FileAPI.upload({
url: '...',
data: { 'session-id': 123 },
files: { ... },
});
<a name="options.uploadMethod"></a>
uploadMethod:String
Request method, HTML5 only.
var xhr = FileAPI.upload({
url: '...',
uploadMethod: 'PUT',
files: { .. },
});
<a name="options.uploadCredentials"></a>
uploadCredentials:Boolean
Pass credentials to upload request, HTML5 only.
var xhr = FileAPI.upload({
url: '...',
uploadCredentials: false,
files: { .. },
});
<a name="options.headers"></a>
headers:Object
Additional request headers, HTML5 only.
var xhr = FileAPI.upload({
url: '...',
headers: { 'x-upload': 'fileapi' },
files: { .. },
});
<a name="options.cache"
