Files
directus/docs/reference/files.md
Bevis Halsey-Perry 0c54f5a9ef Introduce SnippetToggler and New SDK Reference (#19110)
* items semi complete

* updated items page to use snippet toggler and migrated endpoint docs to use it

* updated files page to use snippet toggler and migrated REST and GraphQL endpoint docs to it

* updated activity page to use snippet toggler and migrated REST and GraphQL endpoint doc to it

* updated collections page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* updated dashboards page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated extensions page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated fields page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated flows page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated folders page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated notifications page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated operations page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated panels page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated permissions page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated presets page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated relations page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated revisions page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated roles page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Made headlines consistant with the rest of the doc pages

* Updated server page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated settings page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated shares page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated translations page to use snippet togglers and migrated REST endpoint docs to them

* Updated users page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated utilities page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated webhooks page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated authentication page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* Updated Global Parameters page to use snippet togglers where there are adjacent REST and GraphQL Examples

* Added SDK code snippets to items page and made generic variables consistant

* Added SDK code snippets to files  page and made generic variables consistant

* Few lang changes for files page

* Added SDK code snippets to activity page and made generic variables consistant

* Added SDK code snippets to collections page and made generic variables consistant

* Added SDK code snippets to dashboards page and made generic variables consistant

* removed query word from query parameter objects

* Added SDK code snippets to fields page and made generic variables consistant

* SnippetToggler border

* Used dynamic border color for snippettoggler heading

* Spacing top and bottom of snippet toggler in docs

* Removed extra HRs

* Remove manual TOC in query reference

* Small code styling change in items page

* Updated users page to use snippet togglers and migrated REST and GraphQL endpoint docs to them

* dashboards fixed up property names

* Small copy update on extensions page

* Updated keys in delete mult notifications REST

* Updated keys in operations

* Update keys in panel delete many

* Update keys in permissions

* Added quotes around generic example ID strings

* Added code formatting to final example in share public info

* Format files

* Refined sidebar

* Insert newline before ending template tags

* Fixed extra closing tags, causing an error, un users ref

* Text Formatting Users

* Put GQL related notes inside toggler

* Added SDK code snippets to flows page and made generic variables consistant

* Added SDK code snippets to folder page and made generic variables consistant

* fixing whitepsace for flows and folders page

* Consistent newlines in SnippetToggler usages

* Run prettier

* Fix 'alwaysDark' definition

* Home page snippet toggler style fixes

* Fix snippet toggler lang hover color in light mode

* Introduce different code theme for light mode

* Added SDK code snippets to notifications page and made generic variables consistant

* Switch to 'material-theme-lighter'

* Format file

* Fix tip

* Fix tip in sdk ref

* Consistent spacing for custom containers

* Added SDK code snippets to operations page and made generic variables consistant

* Lint & format code blocks

* Lint & format operations

* Added SDK code snippets to panels page and made generic variables consistant

* Added SDK code snippets to permissions page and made generic variables consistant

* Added SDK code snippets to presets page and made generic variables consistant

* Added SDK code snippets to relations page and made generic variables consistant

* Added SDK code snippets to revisions page and made generic variables consistant

* Added SDK code snippets to roles page and made generic variables consistant

* Added SDK code snippets to server page and made generic variables consistant

* Added SDK code snippets to settings page and made generic variables consistant

* app_url -> directus_project_url

* Omitted auth details in delete multiple files

* Added quotes to values in roles

* Upload a file snippets

* Pluralization for upload/import files

* More files functions typos

* Added SDK code snippets to shares page (still missing createShare(s) as endpoint not functioning currently) and made generic variables consistant

* Added SDK code snippets to translations page (missing delete endponts because not working) and made generic variables consistant

* Added SDK code snippets to users page and made generic variables consistant

* Added SDK code snippets to webhooks page and made generic variables consistant

* Added SDK code snippets to utilites page (except cleaning cache, will be tested and added in later commit) and made generic variables consistant

* Added SDK code snippets to auth page (not login, refresh, and logout though due to errors)

* Added SDK code snippets for utilsExport and clearCache

* added github username be7DOTis to contributors

* Omit auth commands in updateComment

* utilsImport

* rename app_url generic value

* changed instances of updated*operation* to update*Operation*

* missed some 'updated' changse

* Added SDK Snippets to Query Parameters page

* Add section on file security

* added create(s)Shares SDK snippet to shares page

* added console.log to create snippets

* Added delete(s)Webhook SDK snippet to webhooks page

* Added SDK snippets to extensions page

* Added create/updateSingleton section to items page

* Links in files security

* Added SDK Snippets to Schema page

* Added GQL Generic examples to snippet togglers and removed snippet toggler from Login Using SSO Providers

* Added create(s)Presets SDK Snippets to presets page

* replaced fields query in generics snippets for a more generic

* replaced fields query in generics snippets for a more generic

* Use storage value only if valid choice

* Sync snippet togglers across page

* Update docs/reference/system/activity.md

* Update docs/reference/system/activity.md

* Update docs/reference/system/extensions.md

* Update docs/reference/system/revisions.md

* Update docs/reference/system/settings.md

* Update docs/reference/system/revisions.md

* Update docs/reference/system/settings.md

* Update docs/reference/system/activity.md

* Update docs/reference/system/roles.md

* Update docs/reference/system/roles.md

* Update docs/reference/system/roles.md

* Update docs/reference/system/roles.md

* Update docs/reference/system/schema.md

* Update docs/reference/system/server.md

* Update docs/reference/system/shares.md

* Replace all directus_project_url placeholders

* Revert "Sync snippet togglers across page"

This reverts commit 8b36f0d778.

* Update docs/reference/system/shares.md

* Update docs/reference/system/webhooks.md

* Clarify singleton section

* Consistent newlines between SnippetToggler templates

* Format files

* Remove console.log(result) statements from snippet

* Add examples for shares & users

Co-authored-by: Brainslug <tim@brainslug.nl>

* Fix hash GraphQL example

* Clarify update singleton section

* Add auth examples

Co-authored-by: Brainslug <tim@brainslug.nl>

* Final run on consistent newlines between SnippetToggler

* Switch to github themes

* The "Last One"

Co-authored-by: Brainslug <tim@brainslug.nl>

* The "Big One"

* Fix dead links

---------

Co-authored-by: Bevis Halsey-Perry <hi@be7.is>
Co-authored-by: Kevin Lewis <kvn@lws.io>
Co-authored-by: Pascal Jufer <pascal-jufer@bluewin.ch>
Co-authored-by: Brainslug <br41nslug@users.noreply.github.com>
Co-authored-by: rijkvanzanten <rijkvanzanten@me.com>
Co-authored-by: Brainslug <tim@brainslug.nl>
2023-07-25 17:30:37 -04:00

23 KiB

description, readTime, pageClass
description readTime pageClass
REST and GraphQL API documentation for file access and management in Directus. 10 min read page-reference

Accessing Files

Every file managed by the platform is uploaded to the configured storage adapter, and its associated metadata is tracked within the directus_files system collection. Any requested file transformations are handled on the fly, and are only saved to storage.

File Security

Data and permissions around files are associated to the directus_files collection.

It is recommended that you only provide public permissions to specific files or file folders (for example, a 'Public' folder), rather than making the whole collection public. Read more on custom access permissions.

::: warning Exporting Data Creates Files

Exporting data creates new files and adds them to your file storage. If these files are accessible publicly, you may leak data held in the exported collections.

:::

Accessing a File

The location of your actual file originals is based on the project's configuration, but you can consistently access them via the API using the following URL.

example.com/assets/<file-id>
example.com/assets/1ac73658-8b62-4dea-b6da-529fbc9d01a4

::: tip SEO

You can provide an optional filename after the UUID to optimize for SEO, for example:

example.com/assets/<file-id>/<filename>
example.com/assets/1ac73658-8b62-4dea-b6da-529fbc9d01a4/directus-logo.png

This optional filename is also used in the Content-Disposition header when the ?download query parameter is used.

:::

::: warning Direct File Access

While you may technically be able to expose your storage adapters root file system and access your raw files through there, it is recommended that you always use the Directus API. This is the only way that you can take advantage of file permissions and other built-in features.

:::

Original File Original File Used — 602KB and 1800x1200

Downloading a File

To download an asset with the correct filename, you need to add the ?download query parameter to the request and the download attribute to your anchor tag. This will ensure the appropriate Content-Disposition headers are added. Without this, the download will work on the same domain, however it will have the file's "id" as the filename for cross-origin requests.

Example

<a href="https://your-directus.com/assets/<file-id>?download" target="_blank" download="Your File.pdf">Download</a>

Requesting a Thumbnail

Fetching thumbnails is as easy as adding a key query parameter to the original file's URL. In the Admin App, you can configure different asset presets that control the output of any given image. If a requested thumbnail doesn't yet exist, it is dynamically generated and immediately returned.

Preset Transformations

Custom Transformations

Alternatively, if you have "Storage Asset Transform" set to all, you can use the following parameters for more fine grained control:

  • fit — The fit of the thumbnail while always preserving the aspect ratio, can be any of the following options:
    • cover — Covers both width/height by cropping/clipping to fit
    • contain — Contain within both width/height using "letterboxing" as needed
    • inside — Resize to be as large as possible, ensuring dimensions are less than or equal to the requested width and height
    • outside — Resize to be as small as possible, ensuring dimensions are greater than or equal to the requested width and height
  • width — The width of the thumbnail in pixels
  • height — The height of the thumbnail in pixels
  • quality — The optional quality of the thumbnail (1 to 100)
  • withoutEnlargement — Disable image up-scaling
  • format — What file format to return the thumbnail in. One of auto, jpg, png, webp, tiff
    • auto — Will try to format it in webp or avif if the browser supports it, otherwise it will fallback to jpg.

Advanced Transformations

For even more advanced control over the file generation, Directus exposes the full sharp API through the transforms query parameter. This parameter accepts a two-dimensional array with the format [Operation, ...arguments].

Quality vs File Size

The quality parameter can be any integer from 0-100. Qualities closer to 0 have lower file sizes, but also poor image quality due to compression artifacts. Values closer to 100 have larger file sizes, but better image quality. Below are four possible qualities (200x200 cover) to visually compare the balance between compression and file size.

25% 50% 75% 100%
25%
4KB
50%
6KB
75%
8KB
100%
38KB

Preset

example.com/assets/<file-id>?key=<key>

Custom

example.com/assets/<file-id>?fit=<fit>&width=<width>&height=<height>&quality=<quality>
example.com/assets/1ac73658-8b62-4dea-b6da-529fbc9d01a4?fit=cover&width=200&height=200&quality=80

Advanced

?transforms=[
	["blur", 45],
	["tint", "rgb(255, 0, 0)"],
	["expand", { "right": 200, "bottom": 150 }]
]

The File Object

id uuid
Primary key of the file

storage string
Storage adapter used for the file.

filename_disk string
Name of the file as saved on the storage adapter.

filename_download string
Preferred filename when file is downloaded.

title string
Title for the file.

type string
Mimetype of the file.

folder many-to-one
What (virtual) folder the file is in. Many-to-one to folders.

uploaded_by many-to-one
Who uploaded the file. Many-to-one to users.

uploaded_on datetime
When the file was uploaded.

modified_by many-to-one
Who updated the file last. Many-to-one to users.

filesize number
Size of the file in bytes.

width number
If the file is a(n) image/video, it's the width in px.

height number
If the file is a(n) image/video, it's the height in px.

duration number
If the file contains audio/video, it's the duration in milliseconds.

description string
Description of the file.

location string
Location of the file.

tags array
Tags for the file.

metadata object
Any additional metadata Directus was able to scrape from the file. For images, this includes EXIF, IPTC, and ICC information.

{
	"id": "4f4b14fa-a43a-46d0-b7ad-90af5919bebb",
	"storage": "local",
	"filename_disk": "4f4b14fa-a43a-46d0-b7ad-90af5919bebb.jpeg",
	"filename_download": "paulo-silva-vSRgXtQuns8-unsplash.jpg",
	"title": "Paulo Silva (via Unsplash)",
	"type": "image/jpeg",
	"folder": null,
	"uploaded_by": "0bc7b36a-9ba9-4ce0-83f0-0a526f354e07",
	"uploaded_on": "2021-02-04T11:37:41-05:00",
	"modified_by": null,
	"modified_on": "2021-02-04T11:37:42-05:00",
	"filesize": 3442252,
	"width": 3456,
	"height": 5184,
	"duration": null,
	"description": null,
	"location": null,
	"tags": ["photo", "pretty"],
	"metadata": {
		"icc": {
			"version": "2.1",
			"intent": "Perceptual",
			"cmm": "lcms",
			"deviceClass": "Monitor",
			"colorSpace": "RGB",
			"connectionSpace": "XYZ",
			"platform": "Apple",
			"creator": "lcms",
			"description": "c2",
			"copyright": ""
		}
	}
}

List Files

List all files that exist in Directus.

Request

GET /files SEARCH /files

POST /graphql/system

type Query {
	files: [directus_files]
}
import { createDirectus } from '@directus/sdk';
import { rest, readFiles } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(
	readFiles({
		query: {
			query_type: {
				field: {
					query_operator: 'value',
				},
			},
		},
	})
);

Learn more about SEARCH ->

Query Parameters

Supports all global query parameters.

Response

An array of up to limit file objects. If no items are available, data will be an empty array.

Example

GET /files SEARCH /files

query {
	files {
		id
		filename_disk
	}
}
import { createDirectus } from '@directus/sdk';
import { rest, readFiles } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(
	readFiles({
		query: {
			filter: {
				type: {
					_eq: 'image',
				},
			},
		},
	})
);

Retrieve a File

Retrieve a single file by primary key.

Request

GET /files/:id

POST /graphql/system

type Query {
	files_by_id(id: ID!): directus_files
}
import { createDirectus } from '@directus/sdk';
import { rest, readFiles } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(readFile('file_id', query));

Query Parameters

Supports all global query parameters.

Response

Returns a file object if a valid primary key was provided.

Example

GET /files/0fca80c4-d61c-4404-9fd7-6ba86b64154d

POST /graphql/system

query {
	files_by_id(id: "0fca80c4-d61c-4404-9fd7-6ba86b64154d") {
		id
		filename_disk
	}
}
import { createDirectus } from '@directus/sdk';
import { rest, readFiles } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(
	readFile('b3000f41-6ce0-4ba3-b362-fb85c9de8579', {
		fields: ['*'],
	})
);

Upload a File

Upload a new file.

Request

POST /files

Body must be formatted as a multipart/form-data with a final property called file.

Not supported by GraphQL

import { createDirectus } from '@directus/sdk';
import { rest, uploadFiles } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const formData = new FormData();
formData.append('file_1_property', 'Value');
formData.append('file', raw_file);
formData.append('file_2_property', 'Value');
formData.append('file', raw_file_2);

const result = await client.request(uploadFiles(formData));

The file contents has to be provided in a property called file. All other properties of the file object can be provided as well, except filename_disk and filename_download.

::: tip Order Matters

Make sure to define the non-file properties for each file first. This ensures that the file metadata is associated with the correct file.

:::

Query Parameters

Supports all global query parameters.

Response

Returns the file object for the uploaded file, or an array of file objects if multiple files were uploaded at once.

Import a File

Import a file from the web

Request

POST /files/import

{
	"url": "file_url",
	"data": {
		"file_field": "value_1"
	}
}

POST /graphql/system

type Mutation {
	import_file(url: String!, data: create_directus_files_input!): directus_files
}
import { createDirectus } from '@directus/sdk';
import { rest, importFile } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(
	importFile('file_url', {
		file_field: 'value',
	})
);

Query Parameters

Supports all global query parameters.

Request Body

url Required
The URL to download the file from.

data
Any of the file object's properties.

Response

Returns the file object for the imported file.

Example

POST /files/import

{
	"url": "https://source.unsplash.com/random",
	"data": {
		"title": "Example"
	}
}

POST /graphql/system

mutation {
	import_file(url: "https://source.unsplash.com/random", data: { title: "Example" }) {
		id
	}
}
import { createDirectus } from '@directus/sdk';
import { rest, importFile } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(
	importFile('https://upload.wikimedia.org/wikipedia/commons/c/ca/Entlebucher.jpg', {
		title: 'Dog',
	})
);

Update a File

Update an existing file, and/or replace it's file contents.

Request

PATCH /files/:id

{
	"field": "value"
}

POST /graphql/system

type Mutation {
	update_files_item(id: ID!, data: update_directus_files_input!): directus_files
}
import { createDirectus } from '@directus/sdk';
import { rest, updateFile } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(
	updateFile('file_id', {
		file_field: 'value',
	})
);

Query Parameters

Supports all global query parameters.

Request Body

You can either submit a JSON object consisting of a partial file object to update the file meta, or send a multipart/form-data request to replace the file contents on disk. See Upload a File for more information on the structure of this multipart/form-data request.

Response

Returns the file object for the updated file.

Example

PATCH /files/0fca80c4-d61c-4404-9fd7-6ba86b64154d

{
	"title": "Example"
}

POST /graphql/system

mutation {
	update_files_item(id: "0fca80c4-d61c-4404-9fd7-6ba86b64154d", data: { title: "Example" }) {
		id
		title
	}
}
import { createDirectus } from '@directus/sdk';
import { rest, updateFile } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(
	updateFile('dc193671-13b9-4c37-a8af-42f17c036742', {
		title: 'Entlebucher Mountain Dog',
	})
);

Update Multiple Files

Update multiple files at the same time.

Request

PATCH /files

{
	"keys": ["file_id", "file_id_2"],
	"data": {
		"item_field": ["value"]
	}
}

POST /graphql/system

type Mutation {
	update_files_items(ids: [ID!]!, data: update_directus_files!): [directus_files]
}
import { createDirectus } from '@directus/sdk';
import { rest, updateFiles } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(
	updateFiles(['file_id', 'file_id_2'], {
		item_field: ['value'],
	})
);

Query Parameters

Supports all global query parameters.

Request Body

keys Required
Array of primary keys of the files you'd like to update.

data Required
Any of the file object's properties.

Response

Returns the file objects for the updated files.

Example

PATCH /files

{
	"keys": ["b6123925-2fc0-4a30-9d86-863eafc0a6e7", "d17c10aa-0bad-4864-9296-84f522c753e5"],
	"data": {
		"tags": ["cities"]
	}
}

POST /graphql/system

mutation {
	update_files_items(
		ids: ["b6123925-2fc0-4a30-9d86-863eafc0a6e7", "d17c10aa-0bad-4864-9296-84f522c753e5"]
		data: { tags: ["cities"] }
	)
}
import { createDirectus } from '@directus/sdk';
import { rest, updateFiles } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(
	updateFiles(['dc193671-13b9-4c37-a8af-42f17c036742', 'e88b0344-84cf-4bfd-a90b-c0b5b66c17eb'], {
		tags: ['dogs'],
	})
);

Delete a File

Delete an existing file.

::: danger Destructive

This will also delete the file from disk.

:::

Request

DELETE /files/:id

POST /graphql/system

type Mutation {
	delete_files_item(id: ID!): delete_one
}
import { createDirectus } from '@directus/sdk';
import { rest, deleteFile } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(deleteFile('file_id'));

Query Parameters

Supports all global query parameters.

Response

Empty response.

Example

DELETE /files/0fca80c4-d61c-4404-9fd7-6ba86b64154d

POST /graphql/system

mutation {
	delete_files_item(id: "0fca80c4-d61c-4404-9fd7-6ba86b64154d") {
		id
	}
}
import { createDirectus } from '@directus/sdk';
import { rest, deleteFile } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(deleteFile('b3000f41-6ce0-4ba3-b362-fb85c9de8579'));

Delete Multiple Files

Delete multiple files at once.

::: danger Destructive

This will also delete the files from disk.

:::

Request

DELETE /files

["file_id", "file_id"]

POST /graphql/system

type Mutation {
	delete_files_items(ids: [ID!]!): delete_many
}
import { createDirectus } from '@directus/sdk';
import { rest, deleteFiles } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(deleteFiles(['file_id_1', 'file_id_2']));

//or

const result = await client.request(
	deleteFiles({
		query_type: {
			field: {
				query_operator: 'value',
			},
		},
	})
);

Query Parameters

Supports all global query parameters.

Request Body

Array of file primary keys

Returns

Empty response.

Example

DELETE /files

["d17c10aa-0bad-4864-9296-84f522c753e5", "b6123925-2fc0-4a30-9d86-863eafc0a6e7"]

POST /graphql/system

mutation {
	delete_files_items(ids: ["d17c10aa-0bad-4864-9296-84f522c753e5", "b6123925-2fc0-4a30-9d86-863eafc0a6e7"]) {
		ids
	}
}
import { createDirectus } from '@directus/sdk';
import { rest, deleteFiles } from '@directus/sdk/rest';

const client = createDirectus('https://directus.example.com').with(rest());

const result = await client.request(
	deleteFiles(['90a416f0-28e0-4d51-84a2-387d1789add9', '840e2f08-d5cd-4caa-ac0a-31363626efb4'])
);

// or

const result = await client.request(
	deleteFiles({
		filter: {
			type: {
				_eq: 'image/jpeg',
			},
		},
	})
);