Get File

Uploader, Cropper & Resizer


Get File is a plugin which aims to provide an easy way to upload images and other files from a form using AJAX.

In just 5 minutes, you will be able to configure this plugin to save the files selected by the user in your chosen folder using AJAX, without any type of page reloading.

For images you can set Get File for different sizes of the image obtained and placed in the desired folders, you can also activate the crop function, giving the user the possibility to make a cut of the uploaded image to a predefined or free frame and fully adapted for mobile devices.

Get File is a plugin which aims to provide an easy way to upload images and other files from a form using AJAX.

Key features:

Before loading the JS libraries, make sure to load the jQuery and Bootstrap library in your code.
In case jQuery is not present, add the following code:

<script type="text/javascript" src="getfile/libs/jquery/jquery-1.11.1.min.js"></script>

And if you do not have to bootstrap, you can install by adding the following libraries

<link rel="stylesheet" type="text/css href="getfile/libs/bootstrap/css/bootstrap.min.css"">
<link rel="stylesheet" type="text/css href="getfile/libs/bootstrap/css/bootstrap-theme.min.css">
<script type="text/javascript" src="getfile/libs/bootstrap/js/bootstrap.min.js"></script>

To install the plugin Get File, have to add the getfile folder to the root of your project, if you place it in another folder paths listed below should point to the new location.

Finally, you must add the following libraries to the page you want to use this plugin

CSS

Add the following libraries CSS to your page header

<link rel="stylesheet" type="text/css href="getfile/libs/cropper/cropper.css">
<link rel="stylesheet" type="text/css href="getfile/libs/filedrop/filedrop.css">
<link rel="stylesheet" type="text/css href="getfile/css/getfile.css">

JS

Add the following JS libraries to the header of your page

<script type="text/javascript" src="getfile/libs/cropper/cropper.min.js"></script>
<script type="text/javascript" src="getfile/libs/cssloader/js/jquery.cssloader.min.js"></script>
<script type="text/javascript" src="getfile/libs/mobiledetect/mdetect.min.js"></script>
<script type="text/javascript" src="getfile/libs/filedrop/filedrop.min.js"></script>
<script type="text/javascript" src="getfile/js/jquery.getfile.min.js"></script>

Finally, you must place a button or buttons inside our form so your users can use it to upload a file. We have provided the needed CSS code to create a default button. If you need to change its appearance, add the styles you need.

<div id="imageLoaded01" class="btngf btngf-getFile btngf-primary">Select file or image</div>

Each button must have a different ID.

Attention!

The Get File plugin requires two folders writable, a temporary folder where the files once uploaded and destination folder you want to put the files are stored after processing.
In this case we used the /tmp as a temporary folder and the folder /public as the destination folder, both folder should have permissions 777 or 0777.
In your FTP client you can give permissions 777 or 0777, or the following screen may appear to set permissions.

PHP must be enabled EXIF support, necessary for working with metadata of the images and to detect the horientación of images uploaded through mobile devices.
For more information about this extension visit the following link http://php.net/manual/es/book.exif.php

Once the needed libraries are added and the button is located in our form, simply declare the plugin in your JavaScript code configuring your desired options.

$('#imageLoaded01').getFile(
        {
            urlPlugin:      '.',
            folder:         '/public',
            tmpFolder:      '/tmp',
        },
        function(data){
            // this is your callback function
            console.log(data);
        }
);

You also have the option of loading the plugin with the crop or copy function, with a image upload it to your server, so it would not take up any image.

$.getFile(
        {
            urlPlugin:      '.',
            folder:         '/public',
            srcFolder:      '/public',
            srcFile:        'my-image.jpg',
            crop: {
                  active: true,
                  width: 300,
                  height: 200
            }
        },
        function(data){
            // this is your callback function
            console.log(data);
        }
);

The following is a detailed list of all possible options in the Get File plugin:

$('#idButton').getFile(options, callback);

options

* = Mandatory options needed for correct operation.

urlPlugin *

Type: String
Default value: '.'
Description: Relative URL path to the GetFile plugin directory

folder *

Type: String
Default value: null
Description: Path to the directory where the uploaded file will be saved. This folder must have write permissions and the path must start with '/'
Example: '/public/images'

tmpFolder *

Type: String
Default value: null
Description: Temporary directory relative to the document root, which will be used by the plugin to manipulate and edit images. This folder must have write permissions. The path must start with '/'
Example: '/tmp'

srcFolder

Type: String
Default value: null
Description: Path to the directory where the image is. The path must start with '/'
Example: '/public/images'

srcFile

Type: String
Default value: null
Description: Name of the file you want to make the crop.
Example: 'my-image.jpg'

encryption

Type: Boolean
Default value: false
Description: Random file name encryption

filename

Type: String
Default value: null
Description: Final name of the file uploaded to the server, name without extension.

outputExtension

Type: String
Default value: null
Description: The desired extension for an image file. Its possible values are gif, jpg or png
Example: 'jpg'

multiple

Type: Boolean
Default value: false
Description: Enable plugin to allow multiple file uploads. Getfile we can call from a button as shown in the examples or from a <div>, for this tag we can use the class class="drop-zone" to give the appearance of droppable area Example: 'true'

maxFileSize

Type: Integer
Default value: false
Number of bytes allowed for each uploaded file, false to unlimited size
Example: '1024'

maxFilesSizes

Type: Integer
Default value: false
Number of bytes allowed in the total uploaded files, false for unlimited size
Example: '10240'

spinner

Type: Boolean
Default value: true
Using an splinner while loading files

mimesAccept

Type: Array
Default value: [ 'image/*', 'video/*', 'audio/*', 'application/pdf', 'application/msword', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ]
Description: This array contains the MIME type which we want to be allowed into our server. You can set it to false as well in case you want to allow any kind of file.
Caution! Setting the value of mimesAccept to false is not recommended because of server security. You can find a list of MIME types in this link.

By default, it's set to allow the uploading of:

crop (function not available with multiple upload)

Type: Object
Default value: { active: false, width: null, height: null, aspectRatio: null, minSize: null, maxSize: null, setSelect: null }
Description: Object that contains the configuration of the crop feature

Object type, for crop option
active

Type: Boolean
Default value: false,
Description: Determines whether the crop feature is enabled for image uploads

width

Type: Integer
Default value: null,
Description: Width of the cropped image in pixels

height

Type: Integer
Default value: null,
Description: Height of the cropped image in pixels

quality

Type: Integer
Default value: 75
Description: Value of 0-100 to change the image quality, only works with jpg images
Example: 100

overwrite

Type: Boolean
Default value: false
Description: Overwrite file, if there is file with the same name

aspectRatio

Type: Integer
Default value: null,
Description: In case of not defining width and height, this value will be used as the aspect ratio for the crop selection

setData

Type: Objet
Default value: null,
Description: Set default crop area, base on the original image

  • x: the offset left of the cropped area
  • y: the offset top of the cropped area
  • width: the width of the cropped area
  • height: the height of the cropped area
  • rotate: the rotated degrees of the image
Example: {x: 0, y: 0, width:300, height: 200, rotate: 0}

resize

Type: Object
Default value: resize: { active: false, width: null, height: null, constrainProportions: true },
Description: Object that contains the settings for the final image size. This option works only if the image crop functionality is disabled, since the final image size can be defined from there

Object type, for resize option
active

Type: Boolean
Default value: false,
Description: Determines whether the image resize feature is enabled for image uploads

width

Type: Integer
Default value: null,
Description: Width in pixels that will have the image once uploaded to the server

height

Type: Integer
Default value: null,
Description: Height in pixels that will have the image once uploaded to the server

quality

Type: Integer
Default value: 75
Description: Value of 0-100 to change the image quality, only works with jpg images
Example: 100

constrainProportions

Type: Boolean
Default value: true,
Description: Restriction of image proportions. With this property enabled, the image will be resized without affecting the aspect ratio.

copies

Type: Array
Default value: null
Description: Object array. Each object contains a different image size to be obtained from the original image uploaded to the server.

Objects array, for size option

** = Required Options for proper operation of copies option.

folder **

Type: String
Default value: null,
Description: Path to the directory where the image will be saved. This folder must have write permissions and the path must start with '/' Example: '/images/thumbnail'

width

Type: Integer
Default value: null,
Description: Width in pixels of the generated image copy

height

Type: Integer
Default value: null,
Description: Height in pixels of the generated image copy

quality

Type: Integer
Default value: 75
Description: Value of 0-100 to change the image quality, only works with jpg images
Example: 100

constrainProportions

Type: Boolean
Default value: true,
Description: Restriction of image proportions. With this property enabled, the image will be resized without affecting the aspect ratio.

prefix

Type: String
Default value: null,
Description: Prefix that will be added to the name of the image copy

outputExtension

Type: String
Default value: null
Description: Desired extension for the image file. Possible values are jpg, png or gif
Example: 'jpg'

lang

Type: Object
Default value: { cropWindowTitle: 'Crop image', previewTitle: 'Preview', cropButtonText: 'Crop', cancelButtonText: 'Cancel' },
Strings for the image crop popup window. You can translate them to another language if needed

Object, for lang option
cropWindowTitle

Type: String
Default value: 'Crop image',
Description: Popup header text

previewTitle

Type: String
Default value: 'Preview',
Description: Preview window header text

cropButtonText

Type: String
Default value: 'Crop',
Description: Crop button text

cancelButtonText

Type: String
Default value: 'Cancel',
Description: Crop cancel button text

showCropWindow()

Description: Function to back show crop image panel
Code example:

$('#idButton').getFile().showCropWindow();

setOptions(options)

Description: Function to rewrite plugin options
Code example:

$('#idButton').getFile().setOptions(options);

The following is a detailed list of all possible events in the Get File plugin:

getfile:uploaded

Explication: Triggered just after element is uploaded
Code example:

$('#idButton').getFile(options, callback).on('getfile:uploaded', function(event, data){
    // your code
});

getfile:throwresize

Explication: Triggered just before element is resize
Code example:

$('#idButton').getFile(options, callback).on('getfile:throwresize', function(event, data){
    // your code
});

getfile:throwcrop

Explication: Triggered just before throw popup to crop element
Code example:

$('#idButton').getFile(options, callback).on('getfile:throwcrop', function(event, data){
    // your code
});

data property, contains manipulated item properties

The following is a detailed list of all the possible output values you can get from the callback.

{
    "success": true,                                                // Operation done successfully
    "action": "crop",                                               // Last action done. It can be upload, crop, change or resize
    "folder": "/public",                                            // Path to the directory where the uploaded file will be saved
    "size": 40901,                                                  // Size of the file in bytes
    "oldName": "image.png",                                         // Name of the original uploaded file
    "extension": "png",                                             // Extension of the uploaded file
    "mime": "image/png",                                            // MIME type of the uploaded file
    "isImage": true,                                                // Determines whether the file is an image or not
    "name": "e38412321d17fed2b340dca3d2f63fec.png"                  // Final file name
    "coords": {
        "x": "252",                                                 // Selection start X axis coordinate
        "y": "148",                                                 // Selection start Y axis coordinate
        "x2": "428",                                                // Selection end X axis coordinate
        "y2": "265",                                                // Selection end Y axis coordinate
        "w": "176",                                                 // Selection width
        "h": "117"                                                  // Selection height
    },
    "copies": [
        {
            "success": true,                                        // Operation done successfully
            "folder": "/public",                                    // Path to the directory where the uploaded file will be saved
            "name": "e38412321d17fed2b340dca3d2f63fec@2.png"        // Final file name (first image resize)
        },
        {
            "success": true,                                        // Operation done successfully
            "folder": "/public",                                    // Path to the directory where the uploaded file will be saved
            "name": "e38412321d17fed2b340dca3d2f63fec@3.png"        // Final file name (second image resize)
        }
    ]
}

Errores

The following is a detailed list of all the possible errors you can get from the callback.

{
    "success": false,
    "error": 1,
    "message": 'File field is not defined'
}
{
    "success": false,
    "error": 2,
    "message": 'MIME type is not allowed'
}
{
    "success": false,
    "error": 3,
    "message": 'JCrop library not loaded'
}
{
    "success": false,
    "error": 4,
    "message": 'Width and height or ratio must be defined'
}
{
    "success": false,
    "error": 5,
    "message": 'Destination directory does not exist. Check folder setting:'
}
{
    "success": false,
    "error": 6,
    "message": 'Folder setting must be defined'
}
{
    "success": false,
    "error": 7,
    "message": 'Destination folder is not writeable. Please check permissions for:'
}
{
    "success": false,
    "error": 8,
    "message": 'Temp directory does not exist. Check tmpFolder setting:'
}
{
    "success": false,
    "error": 9,
    "message": 'The tmpFolder setting must be defined'
}
{
    "success": false,
    "error": 10,
    "message": 'Destination folder is not writeable. Please check permissions for:'
}
{
    "success": false,
    "error": 11,
    "message": 'The mimesAccept setting must be an array or false. Setting it to false might be dangerous, since it means accepting all file types'
}
{
    "success": false,
    "error": 12,
    "message": 'The path: /path/to/file in the ajax request is not correct, please check the ajax function data'
}
{
    "success": false,
    "error": 13,
    "message": 'The file X weighing XX.XXMb has not been uploaded to the server, to exceed the maximum file size allowed to server'
}
{
    "success": false,
    "error": 14,
    "message": 'Temp file doesn't exist, may be the file uploaded file is too large'
}
{
    "success": false,
    "error": 15,
    "message": 'The file X weighing XX.XX Mb has not been uploaded to the server, to exceed the maximum file size allowed'
}
{
    "success": false,
    "error": 16,
    "message": 'The files whith weighing X.XX Mb they does not been uploaded to the server, to exceed the maximum files sizes allowed of XX.XX Mb'
}
{
    "success": false,
    "error": 17,
    "message": 'Error to delete file, file: /my/file/name, doesn't exist'
}
{
    "success": false,
    "error": 18,
    "message": 'Error, the image river.jpeg could not be copied to the directory: to/directory/'
}
{
    "success": false,
    "error": 19,
    "message": 'Error, please, enabled EXIF extension in your PHP version, to check image orientation'
}
{
    "success": false,
    "error": 100,
    "message": 'Status: 500 Internal Server Error',
    "serverStatus": [
                "memoryUsage": XXXXXX,
                "memoryLimit': XXXXXX,
                "uploadMaxFilesize": XXXXXX,
                "postMaxSize": XXXXXX,
                "maxInputTime": XXXXXX,
                "maxExecutionTime": XXXXXX,
                "fileUploads": XXXXXX
    ]
}

These codes are used and are functional in the file /es-es/index.html

GetFile using only file upload

$('#imageLoaded01').getFile(
        {
            urlPlugin:      '.',
            folder:         '/public',
            tmpFolder:      '/tmp',
        },
        function(data){
            // this is your callback function
            console.log(data);
        }
);

GetFile installed in another directory with image crop enabled

$('#imageLoaded02').getFile(
    {
        urlPlugin:          '../../../plugins',
        folder:             '/public',
        tmpFolder:          '/tmp',
        encryption:         true,
        outputExtension:    'png',
        mimesAccept:    [
            'image/*'
        ],
        crop: {
            active:         true,
            width:          300,
            height:         200,
            aspectRatio:    2
        }
    },
    function(data){
        // this is your callback function
        console.log(data);
    }
);

GetFile with image resizing of the uploaded image

$('#imageLoaded03').getFile(
        {
            urlPlugin:      '.',
            folder:         '/public',
            tmpFolder:      '/tmp',
            resize: {
				active:					false,
				width:					400,
				height:					300,
				constrainProportions:	true
			},
        },
        function(data){
            // this is your callback function
            console.log(data);
        }
);

GetFile with the crop feature enabled, creation of several copies of the image in different sizes and different directories, plus restriction of file uploads to only allow images

$('#imageLoaded04').getFile(
        {
            urlPlugin:          '.',
            folder:             '/public',
            tmpFolder:          '/tmp',
            encryption:         true,
            outputExtension:    'png',
            mimesAccept:    [
                'image/*'
            ],
            crop: {
                active:         true,
                width:          300,
                height:         200,
                aspectRatio:    2
            },
            copies: [
                {
                    width:                  100,
                    height:                 100,
                    constrainProportions:   true,
                    prefix:                 '@2'
                    folder:                 'images/preview',
                    outputExtension:        'png'
                },
                {
                    width:                  50,
                    height:                 50,
                    constrainProportions:   true,
                    prefix:                 '@3',
                    folder:                 'images/thumbnail',
                    outputExtension:        'png'
                }
            ]
        },
        function(data){
            // this is your callback function
            console.log(data);
        }
);

GetFile multiple upload by creating multiple copies of the image in different size and different directories, and restricting file upload only images

$('#imageLoaded05').getFile(
        {
            urlPlugin:          '..',
            folder:             '/public',
            tmpFolder:          '/tmp',
            encryption:         true,
            multiple:           true,
            outputExtension:    'png',
            mimesAccept:        false,
            resize:{
                active:	                true,
                width:	                300,
                height:                 200,
                constrainProportions:	true
            },
            copies: [
                {
                    width:                  100,
                    height:                 100,
                    constrainProportions:   true,
                    prefix:                 '@2x',
                    folder:                 '/public',
                    outputExtension:        'png'
                },
                {
                    width:                  50,
                    height:                 40,
                    prefix:                 '@1x',
                    folder:                 '/public',
                    outputExtension:        'jpg'
                }
            ]
        },
        function(data){
            // this is your callback function
            console.log(data);
        }
);

while upñoad any file, make calls to the callback with the following information:

{
    success:    true,
    action:     "loading",
    totalSize:  xxx,
    total:      xxx,
    loaded:     xxx,
    percentage: xx
}

With this information we can create any progress bar with bootstrap r any other item, attach an example with bootstrap (Available in getfile/libs folder):

HTML Code

<div class="progress">
    <div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100">
        <span class="sr-only"></span>
    </div>
</div>

JavaScript Code

$('#imageLoaded01').getFile(
    {
        urlPlugin:          '..',
        folder:             '/public',
        tmpFolder:          '/tmp'
    },
    function(data)
    {
        if(data.success && data.action == "loading")
        {
            // START CONFIG PROGRESS BAR
            $('#progressBar').html(data.percentage + '%');
            $('#progressBar').attr('aria-valuenow', data.percentage);
            $('#progressBar').css('width', data.percentage + '%');
            // END CONFIG PROGRESS BAR
        }
        else
        {
            // this is your callback function
            console.log(data);
        }
    }
);

Get File allows us to delete an uploaded file, accessing method delete of getFile object, for this example we'll use pluglin jquery.tagsinput (Available in getfile/libs folder) to manage uploaded files, recommend invoke follows

$('#imageLoaded01').getFile(
        {
            urlPlugin:          '..',
            folder:             '/public',
            tmpFolder:          '/tmp'
        },
        function(data)
        {
            // We declare our callback
            if(data.success && data.action == "loading")
            {
                // Code to invoke the progress bar
                $('#progressBar').html(data.percentage + '%');
                $('#progressBar').attr('aria-valuenow', data.percentage);
                $('#progressBar').css('width', data.percentage + '%');
            }
            else
            {
                if(data.success)
                {
                    $('#tags').addTag(data.name); // add a tag to plugin jquery.tagsinput
                    // We keep in store the element, the file name and the object name,
                    // if different directories include directory to the filename.
                    $.data(document, data.name, '#imageLoaded01');
                }
            }
        }
);}

In onRemoveTag from jquery.tagsinput callback element is invoked when an item would delete with this code::

$('#tags').tagsInput({
    'width':        '100%',
    'height':       'auto',
    'interactive':  false,
    'defaultText':  '',
    'onRemoveTag': function(value)
    {
        // value, is the name of the file that we have uploaded,
        // and retrieve from store, the element name that came up previously saved
        var button = $.data(document, value);
        var reference = $(button).data('getFile'); // obtain the getfile object store using the element from which the file was uploaded
        deleteFile(reference, reference.options.folder + '/' + value); // invoke the delete function file
    }
});

The next function we can get inside the previous callback 'onRemoveTag'. To complete the delete function will contain the following code:

function deleteFile(reference, url)
{
    reference.delete(url, function(data) // reference is getFile object and invoke the delete method
    {
        // this is your callback delete function
    });
}

You can see this code and test it in the file /es-es/index.html

Crop popup window customization

This HTML code is automatically added to your page to show the image crop popup window

<!-- start crop window -->
<div style="display:none">
    <div id="wrapGetFile">
        <h3>Crop image</h3>
        <div class="imgs-crop-container"></div>
        <div id="gfPreview">
            <h4 class="title-preview">Preview</h4>
            <div class="imgs-preview-container"></div>
        </div>
        <div id="gfFooter">
            <button type="button" id="gfCropButton" class="btn btn-primary">Crop</button>
            <button type="button" id="gfCancelButton" class="btn">Cancel</button>
        </div>
    </div>
</div>
<!-- end crop window -->

You can customize the popup code editing the file 'getfile/views/popup.php'. Its appearance can be changed with CSS.

Version 4.3 (25/09/2015)

- Fixed translation text with multiple instances
- Add getfile:uploaded event
- Add getfile:throwresize event
- Add getfile:throwcrop event
- Add setOptions function, to rewrite plugin options

Version 4.2.5 (14/09/2015)

- Fixed overwrite function

Version 4.2.4 (01/09/2015)

- Code optimization
- Better compatibility with older browsers
- Update plugin CssLoader
- Corrections minor fixed

Version 4.2.3 (01/08/2015)

- Corrections minor fixed

Version 4.2.1 (17/07/2015)

- Implement overwrite option on crop function
- Implement setData option to set default crop area
- Corrections minor fixed

Version 4.2 (09/07/2015)

- Implement image crop option, from image already uploaded to server
- Corrections minor fixed

Version 4.0 (16/06/2015)

- Change popup by Bootstrap Popup
- Implementation of cropper plugin

Version 3.0 (1/06/2015)

- Change popup by Magnific Popup
- Implementation of Bootstrap

Version 2.3 (18/05/2015)

- Included quality option to resize, crop and copy function on jpg images
- Included function to retrain screen crop "showCropWindow"
- Update CssLoader
- Corrections minor fixed

Version 2.2 (22/01/2015)

- Fully functional examples
- Deprecated TotalSize property to calculate the progress bar, use Total property

Version 2.1 (07/01/2015)

- Fixed problem with spinner

Version 2.0 (25/10/2014)

- Now lets you upload multiple files, crop function not allowed for multiple files
- Change sizes propertie by copies
- Feature erasing files using javascript
- Send to Callback upload progress information
- Ability to limit the size of each file to upload
- Ability to limit the size of files to upload
- Change jquery.mobile.loader library, for cssloader, library very lightweight
- Fixed compatibility issue with Crop function IE11
- We have added more code examples

Version 1.1 (11/09/2014)

- Fixed upload file without crop, resize and extension change
- Corrections on documentation

Version 1.0 (13/08/2014)

- Initial version

For the development of this plugin, the following libraries have been used

Developers who have contributed: