Save an uploaded file
A form uploads the file weekly.txt. This program saves it in the folder uploads.
<?nvs// This program saves an uploaded file in a folder.string $folder = Core\Path::join(Core\IO::createTemporaryDirectory(), 'uploads');Core\IO::makeDirectory($folder);
foreach (Core\Request::files() as Core\Request\Part $part) { // The client chose the file name, so the program uses its own name. string $path = Core\Path::join($folder, Core\Uuid::v4() . '.txt'); // `saveTo` writes the file. It keeps only a small part of it in memory at a time. $part->saveTo($path, { max: 1000000 }); echo 'saved ', $part->filename(), ', ', Core\IO::size($path), " bytes\n";}saved weekly.txt, 38 bytesBy default, a request writes only in folders that Core\IO::createTemporaryDirectory created for it. To save
uploads in another folder, allow writing in nvs.toml, as the file in the same folder does:
[capabilities.fs]write = trueCore\Request::files returns each uploaded file as a Core\Request\Part. saveTo writes the
file to a path. max is the largest size in bytes. A larger file throws a RuntimeError.
The program does not use the file name from the client. A name like ../../config.toml could
point outside the folder. Core\Uuid::v4 gives a new name that is different each time.
The server checks a CSRF token (a value that proves the form came from your own page) for each
Post request. A form that uploads a file sends multipart/form-data, and the server does not read
the token from that body. So the form carries the token in the URL of its action:
<form method="post" action="/upload?_csrf={$token}" enctype="multipart/form-data">
The page that shows the form sets $token with
Core\Csrf::token(). You do not need to start a session first.
Read Core\Request for the other parts of a form.
