PHP code example of gravitypdf / upload

1. Go to this page and download the library: Download gravitypdf/upload library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gravitypdf / upload example snippets


$storage = new \GravityPdf\Upload\Storage\FileSystem('/path/to/directory');
// To override existing files when uploading, pass `true` as the second parameter
// $storage = new \GravityPdf\Upload\Storage\FileSystem('/path/to/directory', true);
$file = new \GravityPdf\Upload\File('foo', $storage);

// Validate file upload
// MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml
$file->addValidations([
    // Ensure file is of type "image/png"
    new \GravityPdf\Upload\Validation\Mimetype('image/png'),
    new \GravityPdf\Upload\Validation\Extension('png'),

    //You can also add multi mimetype validation or extensions
    //new \GravityPdf\Upload\Validation\Mimetype(['image/png', 'image/gif'])
    //new \GravityPdf\Upload\Validation\Extension(['png', 'gif']),

    // Ensure file is no larger than 5M (use "B", "K", M", or "G")
    new \GravityPdf\Upload\Validation\Size('5M'),
]);

// Access data about the file
// If upload accepts multiple files an array will be returned for each of these
$data = [
    'name' => $file->getNameWithExtension(),
    'extension' => $file->getExtension(),
    'mime' => $file->getMimetype(),
    'size' => $file->getSize(),
    'md5' => $file->getMd5(),
    'dimensions' => $file->getDimensions(),
];

// If you have an upload field that accepts multiple files you can access each file's info individually
$firstFileName = $file[0]->getNameWithExtension();
if(isset($file[1])) {
    $secondFileName = $file[1]->getNameWithExtension();
}

// or loop over all files for this key
foreach($file as $i => $upload) {
    $name = $upload->getNameWithExtension();
    $upload->setName('file-'.$i);
}

// Try to upload file(s)
try {
    // Success!
    $file->upload();
} catch (\Exception $e) {
    // Validation errors
    $errors = $file->getErrors();
    if(count($errors) === 0) {
        // Failed for another reason, like the file already exists
        $error = $e->getMessage();
    }
}