Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## unreleased

- A file input with `multiple` now keeps every selected file, instead of only the last one. The new [`sqlpage.persist_uploaded_files`](https://sql-page.com/functions.sql?function=persist_uploaded_files) function saves them all and returns their paths as a JSON array.

## v0.48.0 (2026-11-12)

- Updated Rust and browser dependencies, including ApexCharts 8.8.1, Tabler 1.7.4, Tabler icons 3.51, and Tom Select 2.7. Chart series names and labels now display HTML as text, fixing upstream script injection in legends and tooltips.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ INSERT INTO parameter(component, name, description, type, top_level, optional) S
('min', 'The minimum value to accept for an input of type number', 'REAL', FALSE, TRUE),
('max', 'The maximum value to accept for an input of type number', 'REAL', FALSE, TRUE),
('checked', 'Used only for checkboxes and radio buttons. Indicates whether the checkbox should appear as already checked.', 'BOOLEAN', FALSE, TRUE),
('multiple', 'Used only for select elements. Indicates that multiple elements can be selected simultaneously. When using multiple, you should add square brackets after the variable name: ''my_variable[]'' as name', 'BOOLEAN', FALSE, TRUE),
('multiple', 'For select elements, indicates that multiple elements can be selected simultaneously. When using multiple, you should add square brackets after the variable name: ''my_variable[]'' as name. For file inputs, lets the user select several files at once: save them all with [sqlpage.persist_uploaded_files](functions.sql?function=persist_uploaded_files).', 'BOOLEAN', FALSE, TRUE),
('empty_option', 'Only for inputs of type `select`. Adds an empty option with the given label before the ones defined in `options`. Useful when generating other options from a database table.', 'TEXT', FALSE, TRUE),
('searchable', 'For select and multiple-select elements, displays them with a nice dropdown that allows searching for options.', 'BOOLEAN', FALSE, TRUE),
('dropdown', 'An alias for "searchable".', 'BOOLEAN', FALSE, TRUE),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
INSERT INTO sqlpage_functions (
"name",
"introduced_in_version",
"icon",
"description_md"
)
VALUES (
'persist_uploaded_files',
'0.49.0',
'files',
'Persists all the files uploaded in a single form field, and returns their paths as a JSON array.
If no file was uploaded in the field, the function returns NULL.

Use it with a file input that has the `multiple` attribute, so that users can select several files at once.
It works like [`persist_uploaded_file`](?function=persist_uploaded_file),
which only persists one file (the last one, when several were sent).

If one of the files has an extension that is not allowed, the function fails and no file is persisted.

### Example

#### Photo gallery

##### `upload_form.sql`

```sql
select ''form'' as component, ''save_photos.sql'' as action;
select ''file'' as type, ''photos[]'' as name, ''Photos'' as label, true as multiple, ''image/*'' as accept;
```

##### `save_photos.sql`

```sql
set paths = sqlpage.persist_uploaded_files(''photos'', ''photos'', ''jpg,jpeg,png,webp'');

insert into photo (path)
select value from json_each($paths); -- PostgreSQL: json_array_elements_text($paths::json)

select ''redirect'' as component, ''gallery.sql'' as link;
```
'
);
INSERT INTO sqlpage_function_parameters (
"function",
"index",
"name",
"description_md",
"type"
)
VALUES (
'persist_uploaded_files',
1,
'files',
'Name of the form field containing the uploaded files. A field named `photos[]` in the form can be referenced as `photos`.',
'TEXT'
),
(
'persist_uploaded_files',
2,
'destination_folder',
'Optional. Path to the folder where the files will be saved, relative to the web root. By default, the files will be saved in the `uploads` folder.

**Security note**: this value must be a folder name you choose yourself in your SQL code (a trusted constant). Never build it from untrusted input: see [`persist_uploaded_file`](?function=persist_uploaded_file).',
'TEXT'
),
(
'persist_uploaded_files',
3,
'allowed_extensions',
'Optional. Comma-separated list of allowed file extensions, checked for every file. By default: jpg,jpeg,png,gif,bmp,webp,pdf,txt,doc,docx,xls,xlsx,csv,mp3,mp4,wav,avi,mov.
Changing this may be dangerous ! If you add "sql", "svg" or "html" to the list, an attacker could execute arbitrary SQL queries on your database, or impersonate other users.',
'TEXT'
),
(
'persist_uploaded_files',
4,
'mode',
'Optional. Unix permissions to set on the files, in octal notation. By default, "600" (read/write for the owner only).',
'TEXT'
);
2 changes: 2 additions & 0 deletions src/webserver/database/sqlpage_functions/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ mod link;
mod oidc_logout_url;
mod path;
mod persist_uploaded_file;
mod persist_uploaded_files;
mod protocol;
mod random_string;
mod read_file_as_data_url;
Expand Down Expand Up @@ -67,6 +68,7 @@ sqlpage_functions! {
oidc_logout_url,
path,
persist_uploaded_file,
persist_uploaded_files,
protocol,
random_string,
read_file_as_data_url,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use std::borrow::Cow;

use anyhow::Context;

use actix_multipart::form::tempfile::TempFile;

use crate::webserver::http_request_info::RequestInfo;

use super::random_string::random_string_sync;
Expand All @@ -16,13 +18,30 @@ pub(super) async fn persist_uploaded_file<'a>(
allowed_extensions: Option<Cow<'a, str>>,
mode: Option<Cow<'a, str>>,
) -> anyhow::Result<Option<String>> {
let folder = folder.unwrap_or(Cow::Borrowed("uploads"));
let allowed_extensions_str =
allowed_extensions.unwrap_or(Cow::Borrowed(DEFAULT_ALLOWED_EXTENSIONS));
let allowed_extensions = allowed_extensions_str.split(',');
let Some(uploaded_file) = request.uploaded_files.get(&field_name.to_string()) else {
let Some(uploaded_file) = request.uploaded_files.get(&field_name) else {
return Ok(None);
};
let extension = allowed_extension(uploaded_file, allowed_extensions.as_deref())?;
let path = persist_file(
request,
uploaded_file,
extension,
&field_name,
folder.as_deref(),
mode.as_deref(),
)
.await?;
Ok(Some(path))
}

/// Returns the extension of the uploaded file, or an error if it is not in the allowed list.
pub(super) fn allowed_extension<'f>(
uploaded_file: &'f TempFile,
allowed_extensions: Option<&str>,
) -> anyhow::Result<&'f str> {
let allowed_extensions = allowed_extensions
.unwrap_or(DEFAULT_ALLOWED_EXTENSIONS)
.split(',');
let file_name = uploaded_file.file_name.as_deref().unwrap_or_default();
let extension = file_name.split('.').next_back().unwrap_or_default();
if !allowed_extensions
Expand All @@ -32,14 +51,28 @@ pub(super) async fn persist_uploaded_file<'a>(
let exts = allowed_extensions.collect::<Vec<_>>().join(", ");
anyhow::bail!("file extension {extension} is not allowed. Allowed extensions: {exts}");
}
Ok(extension)
}

/// Copies an uploaded file to `folder` (relative to the web root) under a random name,
/// and returns its path relative to the web root, with a leading slash.
pub(super) async fn persist_file(
request: &RequestInfo,
uploaded_file: &TempFile,
extension: &str,
field_name: &str,
folder: Option<&str>,
mode: Option<&str>,
) -> anyhow::Result<String> {
let folder = folder.unwrap_or("uploads");
// Resolve the folder path relative to the web root.
// `folder` is trusted application input: it is expected to be a constant chosen by the
// app author in their SQL code, never attacker-controlled request data. It is joined
// directly to the web root, so a `folder` containing `..` or an absolute path would let
// the caller write the uploaded file outside the web root. Callers must not pass
// untrusted input (form fields, query parameters, headers, ...) as the folder.
let web_root = &request.app_state.config.web_root;
let target_folder = web_root.join(&*folder);
let target_folder = web_root.join(folder);
// create the folder if it doesn't exist
tokio::fs::create_dir_all(&target_folder)
.await
Expand All @@ -56,7 +89,7 @@ pub(super) async fn persist_uploaded_file<'a>(
target_path.display()
)
})?;
set_file_mode(&target_path, mode.as_deref()).await?;
set_file_mode(&target_path, mode).await?;
// remove the WEB_ROOT prefix from the path, but keep the leading slash
let path = "/".to_string()
+ target_path
Expand All @@ -68,7 +101,7 @@ pub(super) async fn persist_uploaded_file<'a>(
target_path.display()
)
})?;
Ok(Some(path))
Ok(path)
}

#[cfg(unix)]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use std::borrow::Cow;

use crate::webserver::http_request_info::RequestInfo;

use super::persist_uploaded_file::{allowed_extension, persist_file};

/// Persists all the files uploaded in a field (a file input with the `multiple` attribute),
/// and returns their paths as a JSON array. Returns NULL if no file was uploaded.
pub(super) async fn persist_uploaded_files<'a>(
request: &'a RequestInfo,
field_name: Cow<'a, str>,
folder: Option<Cow<'a, str>>,
allowed_extensions: Option<Cow<'a, str>>,
mode: Option<Cow<'a, str>>,
) -> anyhow::Result<Option<String>> {
let files: Vec<_> = request.uploaded_files.all(&field_name).collect();
if files.is_empty() {
return Ok(None);
}
// Check every extension before writing anything: a rejected file leaves no partial upload behind.
let extensions = files
.iter()
.map(|file| allowed_extension(file, allowed_extensions.as_deref()))
.collect::<anyhow::Result<Vec<_>>>()?;
let mut paths = Vec::with_capacity(files.len());
for (file, extension) in files.into_iter().zip(extensions) {
paths.push(
persist_file(
request,
file,
extension,
&field_name,
folder.as_deref(),
mode.as_deref(),
)
.await?,
);
}
Ok(Some(serde_json::to_string(&paths)?))
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub(super) async fn uploaded_file_mime_type<'a>(
) -> Option<Cow<'a, str>> {
let mime = request
.uploaded_files
.get(&*upload_name)?
.get(&upload_name)?
.content_type
.as_ref()?;
Some(Cow::Borrowed(mime.as_ref()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub(super) async fn uploaded_file_name<'a>(
) -> Option<Cow<'a, str>> {
let fname = request
.uploaded_files
.get(&*upload_name)?
.get(&upload_name)?
.file_name
.as_ref()?;
Some(Cow::Borrowed(fname.as_str()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ pub(super) async fn uploaded_file_path<'a>(
request: &'a RequestInfo,
upload_name: Cow<'a, str>,
) -> Option<Cow<'a, str>> {
let uploaded_file = request.uploaded_files.get(&*upload_name)?;
let uploaded_file = request.uploaded_files.get(&upload_name)?;
Some(uploaded_file.file.path().to_string_lossy())
}
Loading
Loading