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
54 changes: 54 additions & 0 deletions examples/official-site/content/functions/persist_uploaded_file.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
icon: device-floppy
since: 0.20.1
category: files-and-uploads
summary: Save an uploaded file and return its path.
parameters:
- name: file
type: TEXT
required: true
description: Name of the form field containing the uploaded file. The current page must be referenced in
the `action` property of a `form` component that contains a file input field.
- name: destination_folder
type: TEXT
description: |-
Optional. Path to the folder where the file will be saved, relative to the web root (the root folder of your website files). By default, the file 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 such as a form field, a query parameter, a request header, or anything else the visitor controls. The folder is joined directly to the web root, so a value containing `..` or an absolute path would cause the uploaded file to be written *outside* the web root, anywhere the SQLPage process can write. Keeping `destination_folder` a fixed value chosen by the application author avoids this.
- name: allowed_extensions
type: TEXT
description: |-
Optional. Comma-separated list of allowed file extensions. 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.
- name: mode
type: TEXT
description: |-
Optional. Unix permissions to set on the file, in octal notation. By default, the file will be saved with "600" (read/write for the owner only).
Octal notation works by using three digits from 0 to 7: the first for the owner, the second for the group, and the third for others.
For example, "644" means read/write for the owner, and read-only for others.
[Learn more about numeric notation for file-system permissions on Wikipedia](https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation).
---

Persists an uploaded file to the local filesystem, and returns its path.
If the file input field is empty, the function returns NULL.

### Example

#### User profile picture

##### `upload_form.sql`

```sql
select 'form' as component, 'persist_uploaded_file.sql' as action;
select 'file' as type, 'profile_picture' as name, 'Upload your profile picture' as label;
```

##### `persist_uploaded_file.sql`

```sql
update user
set profile_picture = sqlpage.persist_uploaded_file('profile_picture', 'profile_pictures', 'jpg,jpeg,png,gif,webp')
where id = (
select user_id from session where session_id = sqlpage.cookie('session_id')
);
```
66 changes: 66 additions & 0 deletions examples/official-site/content/functions/persist_uploaded_files.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
icon: files
since: 0.49.0
category: files-and-uploads
summary: Save multiple uploads from one field and return their file details.
parameters:
- name: files
type: TEXT
required: true
description: Name of the form field containing the uploaded files. A field named `photos[]` in the form
can be referenced as `photos`.
- name: destination_folder
type: TEXT
description: |-
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).
- name: allowed_extensions
type: TEXT
description: |-
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.
- name: mode
type: TEXT
description: Optional. Unix permissions to set on the files, in octal notation. By default, "600" (read/write
for the owner only).
---

Persists all the files uploaded in a single form field, and returns a JSON array with one object per file:

- `path`: where the file was saved, relative to the web root (like the return value of [`persist_uploaded_file`](?function=persist_uploaded_file)),
- `name`: the original name of the file on the user's device,
- `mime_type`: the type of the file, as sent by the browser,
- `size`: the size of the file, in bytes.

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, or cannot be saved, 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 files = sqlpage.persist_uploaded_files('photos', 'photos', 'jpg,jpeg,png,webp');

-- SQLite (PostgreSQL: json_array_elements($files::json), SQL Server: OPENJSON($files))
insert into photo (local_path, name, mime_type, size)
select value ->> 'path', value ->> 'name', value ->> 'mime_type', value ->> 'size'
from json_each($files);

select 'redirect' as component, 'gallery.sql' as link;
```
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
-- Insert the 'variables' function into sqlpage_functions table
INSERT INTO sqlpage_functions (
"name",
"introduced_in_version",
"icon",
"description_md"
)
VALUES (
'read_file_as_data_url',
'0.17.0',
'file-dollar',
'Returns a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs)
---
icon: file-dollar
since: 0.17.0
category: files-and-uploads
summary: Read a file as a data URL for embedding in a page.
parameters:
- name: name
type: TEXT
required: true
description: Path to the file to read.
---

Returns a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs)
containing the contents of the given file.

The file path is relative to the `web root` directory, which is the directory from which your website is served.
Expand All @@ -18,7 +19,7 @@ with the `web_root` [configuration option](https://github.com/sqlpage/SQLPage/bl

If the given argument is null, the function will return null.

As with other functions, if an error occurs during execution
As with other functions, if an error occurs during execution
(because the file does not exist, for instance),
the function will display an error message and the
database query will not be executed.
Expand All @@ -37,30 +38,12 @@ Otherwise, the MIME type will be guessed from the file extension, without lookin


## Example: inlining a picture

```sql
select ''card'' as component;
select ''Picture'' as title, sqlpage.read_file_as_data_url(''/path/to/picture.jpg'') as top_image;
select 'card' as component;
select 'Picture' as title, sqlpage.read_file_as_data_url('/path/to/picture.jpg') as top_image;
```

> **Note:** Data URLs are larger than the original file they represent, so they should only be used for small files
> (under a few hundred kilobytes).
> Otherwise, the page will take a long time to load.
');

-- Insert the parameters for the 'variables' function into sqlpage_function_parameters table
-- Parameter 1: 'method' parameter
INSERT INTO sqlpage_function_parameters (
"function",
"index",
"name",
"description_md",
"type"
)
VALUES (
'read_file_as_data_url',
1,
'name',
'Path to the file to read.',
'TEXT'
);
37 changes: 37 additions & 0 deletions examples/official-site/content/functions/read_file_as_text.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
icon: file-invoice
since: 0.17.0
category: files-and-uploads
summary: Read the text of a UTF-8 file from the web root.
parameters:
- name: name
type: TEXT
required: true
description: Path to the file to read.
---

Returns a string containing the contents of the given file.

The file must be a raw text file using UTF-8 encoding.

The file path is relative to the `web root` directory, which is the directory from which your website is served
(not necessarily the directory SQLPage is launched from).

If the given argument is null, the function will return null.

As with other functions, if an error occurs during execution
(because the file does not exist, for instance),
the function will display an error message and the
database query will not be executed.

If you are using a `sqlpage_files` table to store files directly in the database (serverless mode),
the function will attempt to read the file from the database filesystem if it is not found on the local disk,
using the same logic as for serving files in response to HTTP requests.

## Example

### Rendering a markdown file

```sql
select 'text' as component, sqlpage.read_file_as_text('/path/to/file.md') as contents_md;
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
icon: file-settings
since: 0.18.0
category: files-and-uploads
summary: Read the media type supplied by the browser for an uploaded file.
parameters:
- name: name
type: TEXT
required: true
description: Name of the file input field in the form.
---

Returns the MIME type of an uploaded file.

## Example: handling a picture upload

When letting the user upload a picture, you may want to check that the uploaded file is indeed an image.

```sql
select 'redirect' as component,
'invalid_file.sql' as link
where sqlpage.uploaded_file_mime_type('myfile') not like 'image/%';
```

In `invalid_file.sql`, you can display an error message to the user:

```sql
select 'alert' as component, 'Error' as title,
'Invalid file type' as description,
'alert-circle' as icon, 'red' as color;
```

## Example: white-listing file types

You could have a database table containing the allowed MIME types, and check that the uploaded file is of one of those types:

```sql
select 'redirect' as component,
'invalid_file.sql' as link
where sqlpage.uploaded_file_mime_type('myfile') not in (select mime_type from allowed_mime_types);
```
54 changes: 54 additions & 0 deletions examples/official-site/content/functions/uploaded_file_name.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
icon: file-description
since: 0.23.0
category: files-and-uploads
summary: Read the original filename supplied by the browser.
parameters:
- name: name
type: TEXT
required: true
description: Name of the file input field in the form.
---

Returns the `filename` value in the `content-disposition` header.

## Example: saving uploaded file metadata for later download

### Making a form

```sql
select 'form' as component, 'handle_file_upload.sql' as action;
select 'myfile' as name, 'file' as type, 'File' as label;
```

### Handling the form response

### Inserting an arbitrary file as a [data URL](https://en.wikipedia.org/wiki/Data_URI_scheme) into the database

In `handle_file_upload.sql`, one can process the form results like this:

```sql
insert into uploaded_files (fname, content, uploaded) values (
sqlpage.uploaded_file_name('myfile'),
sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path('myfile')),
CURRENT_TIMESTAMP
);
```

> *Note*: Data URLs are larger than the original file, so it is not recommended to use them for large files.

### Downloading the uploaded files

The file can be downloaded by clicking a link like this:
```sql
select 'button' as component;
select name as title, content as link from uploaded_files where name = $file_name limit 1;
```

> *Note*: because the file is ecoded as a data uri, the file is transferred to the client whether or not the link is clicked

### Large files

See the [`sqlpage.uploaded_file_path`](?function=uploaded_file_path#function) function.

See the [`sqlpage.persist_uploaded_file`](?function=persist_uploaded_file#function) function.
Loading
Loading