Filepond is a JavaScript library that can upload anything you throw at it, optimizes images for faster uploads, and offers a great, accessible, silky smooth user experience.
Features.
- Accepts directories, files, blobs, local URLs, remote URLs and Data URIs.
- Drop files, select on filesystem, copy and paste files, or add files using the API.
- Async uploads with AJAX, supports chunk uploads, can encode files as base64 data and send along form post.
- Accessible, tested with AT software like VoiceOver and JAWS, navigable by Keyboard.
- Image optimization, automatic image resizing, cropping, filtering, and fixes EXIF orientation.
- Responsive, automatically scales to available space, is functional on both mobile and desktop devices.
Installation.
The preferred way to install this extension is through composer.
Either run.
composer require --dev --prefer-dist yii2-extensions/filepond
or add to the require section of your composer.json file.
"yii2-extensions/filepond": "dev-main"
Usage in controller or Model.
use Yii2\Extensions\Filepond\FileProcessing;
$imageFile = FileProcessing::saveWithReturningFile(
$categoryForm->image_file,
Yii::getAlias('@uploads'),
"category{$category->id}",
false
);
Using the FileProcessing helper, we obtain the file name. As we can observe, we pass as arguments to the saveWithReturningFile method, the data (in this case, the form property), the directory where we will save the file, the name we will assign to it, and whether we want the full path of the file.
Usage in view.
use Yii2\Extensions\FilePond\FilePond;
<?=
$form
->field($formModel, 'image_file')
->widget(
FilePond::class,
[
'loadFileDefault' => $imageFile,
'imagePreviewHeight' => 170,
'imageCropAspectRatio' => '1:1',
],
)
?>
In your Filepond widget configuration, the key 'acceptedFileTypes' is used to define the types of files that the widget will allow for upload. Here, the value ['image/svg+xml'] specifies that only files with the MIME type image/svg+xml, which corresponds to SVG files, are permitted to be uploaded through this widget.
This setting ensures that when users attempt to upload a file, the widget will only accept files that match the specified MIME type (in this case, SVG files) and reject any other file types.
With Filepond, we don't need to rely on Yii2 helpers or validations for file uploads.
Happy coding!