Input.uploadedFile
Input.uploadedFile($fieldName, $uploadDir, $allowedExtensions, $maxFileSizeMb=0) -> Result
Description
Returns a Result object for the given $fieldName
.
If the file passes validation, calling $result.get()
will return a FilePathString to the file.
For security, the file will be written to $uploadDir
with a randomized filename.
If $uploadDir
does not exist, it will be created.
Validation Checks
A file is not valid in the following cases:
- Illegal file name patterns (e.g. '..')
- Common evasion tactics (e.g. double extensions)
- File extension is not within list of
$allowedExtensions
- File MIME type (as detected by the file content) does not match file extension.
Example
// HTML tag: // <input type="file" name="config"> $result = Input.uploadedFile('config', dir'app:/data/files/configs', 'json,xml') if $result.isOk() { print($result.get()) //= Ex: '/yourapp/data/files/configs/fjwgSj73Fjs4q434q.json' }
Complete example:
fun main { $page = Page.create({ main: formHtml() }) Output.sendPage($page) } // This will automatically get called instead of 'main' when // the form is submitted. fun mainPost { $result = Input.uploadedFile('config', dir'configs', 'json') if $result.isOk() { $file = $result.get() $content = $file.read(-join) $dataMap = Json.decode($content) print($dataMap) } else { print($result.getFailCode()) } } // Note: Upload forms need enctype="multipart/form-data". tem formHtml { <h1> Upload Config File <form action="/upload" method="post" enctype="multipart/form-data"> {{ Web.csrfToken(true) }} <input type="file" name="config"> <small> Supported files: .json, .xml <button type="submit">Upload</button> </> }