filesystem

import filesystem "ganigeorgiev.com/pocketbase/pocketbase/tools/filesystem"

Source: tools/filesystem.

Constants

const MetadataOriginalName = "original-filename"

Variables

var ErrNotFound = blob.ErrNotFound

note: the same as blob.ErrNotFound for backward compatibility with earlier versions

var ThumbSizeRegex = regexp.MustCompile(`^(\d+)x(\d+)(t|b|f)?$`)

Types

BytesReader

type BytesReader struct {
	Bytes []byte
}

BytesReader defines a FileReader from bytes content.

BytesReader.Open

func (r *BytesReader) Open() (io.ReadSeekCloser, error)

Open implements the filesystem.FileReader interface.

DeleteEvent

type DeleteEvent struct {
	hook.Event
	Filesystem *System
	FileKey    string
}

File

type File struct {
	Reader       FileReader `form:"-" json:"-" xml:"-"`
	Name         string     `form:"name" json:"name" xml:"name"`
	OriginalName string     `form:"originalName" json:"originalName" xml:"originalName"`
	Size         int64      `form:"size" json:"size" xml:"size"`
}

File defines a single file io.ReadSeekCloser resource.

The file could be from a local path, multipart/form-data header, etc.

NewFileFromBytes

func NewFileFromBytes(b []byte, name string) (*File, error)

NewFileFromBytes creates a new File instance from the provided byte slice.

NewFileFromMultipart

func NewFileFromMultipart(mh *multipart.FileHeader) (*File, error)

NewFileFromMultipart creates a new File from the provided multipart header.

NewFileFromPath

func NewFileFromPath(path string) (*File, error)

NewFileFromPath creates a new File instance from the provided local file path.

NewFileFromURL

func NewFileFromURL(ctx context.Context, url string) (*File, error)

NewFileFromURL creates a new File from the provided url by downloading the resource and load it as BytesReader.

Example

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

file, err := filesystem.NewFileFromURL(ctx, "https://example.com/image.png")

File.AsMap

func (f *File) AsMap() map[string]any

AsMap implements [core.mapExtractor] and returns a value suitable to be used in an API rule expression.

FileReader

type FileReader interface {
	Open() (io.ReadSeekCloser, error)
}

FileReader defines an interface for a file resource reader.

MultipartReader

type MultipartReader struct {
	Header *multipart.FileHeader
}

MultipartReader defines a FileReader from multipart.FileHeader.

MultipartReader.Open

func (r *MultipartReader) Open() (io.ReadSeekCloser, error)

Open implements the filesystem.FileReader interface.

NewWriterEvent

type NewWriterEvent struct {
	hook.Event
	Filesystem *System
	FileKey    string
	Options    *blob.WriterOptions
	Writer     *blob.Writer // filled only after e.Next()
}

PathReader

type PathReader struct {
	Path string
}

PathReader defines a FileReader from a local file path.

PathReader.Open

func (r *PathReader) Open() (io.ReadSeekCloser, error)

Open implements the filesystem.FileReader interface.

System

type System struct {
	// contains filtered or unexported fields
}

New

func New(drv blob.Driver) *System

PocketOne: New initializes a filesystem over any blob driver (e.g. one that wraps another filesystem's driver, see System.Driver).

NB! Make sure to call `Close()` after you are done working with it.

NewLocal

func NewLocal(dirPath string) (*System, error)

NewLocal initializes a new local filesystem instance.

NB! Make sure to call `Close()` after you are done working with it.

NewS3

func NewS3(
	bucketName string,
	region string,
	endpoint string,
	accessKey string,
	secretKey string,
	s3ForcePathStyle bool,
) (*System, error)

NewS3 initializes a new S3 filesystem instance.

NB! Make sure to call `Close()` after you are done working with it.

System.Attributes

func (s *System) Attributes(fileKey string) (*blob.Attributes, error)

Attributes returns the attributes for the file with fileKey path.

If the file doesn't exist it returns ErrNotFound.

System.Close

func (s *System) Close() error

Close releases any resources used for the related filesystem.

System.Copy

func (s *System) Copy(srcKey, dstKey string) error

Copy copies the file stored at srcKey to dstKey.

If srcKey file doesn't exist, it returns ErrNotFound.

If dstKey file already exists, it is overwritten.

System.CreateThumb

func (s *System) CreateThumb(originalKey, thumbKey, thumbSize string) error

CreateThumb creates a new thumb image for the file at originalKey location. The new thumb file is stored at thumbKey location.

thumbSize is in the format: - 0xH (eg. 0x100) - resize to H height preserving the aspect ratio - Wx0 (eg. 300x0) - resize to W width preserving the aspect ratio - WxH (eg. 300x100) - resize and crop to WxH viewbox (from center) - WxHt (eg. 300x100t) - resize and crop to WxH viewbox (from top) - WxHb (eg. 300x100b) - resize and crop to WxH viewbox (from bottom) - WxHf (eg. 300x100f) - fit inside a WxH viewbox (without cropping)

System.Delete

func (s *System) Delete(fileKey string) error

Delete deletes stored file at fileKey location.

If the file doesn't exist returns ErrNotFound.

System.DeletePrefix

func (s *System) DeletePrefix(prefix string) []error

DeletePrefix deletes everything starting with the specified prefix.

The prefix could be subpath (ex. "/a/b/") or filename prefix (ex. "/a/b/file_").

System.Driver

func (s *System) Driver() blob.Driver

PocketOne: Driver returns the filesystem's blob driver, e.g. to wrap it and pass it to New.

System.Exists

func (s *System) Exists(fileKey string) (bool, error)

Exists checks if file with fileKey path exists or not.

System.GetFile

func (s *System) GetFile(fileKey string) (*blob.Reader, error)

Deprecated: Please use GetReader(fileKey) instead.

System.GetReader

func (s *System) GetReader(fileKey string) (*blob.Reader, error)

GetReader returns a file content reader for the given fileKey.

NB! Make sure to call Close() on the file after you are done working with it.

If the file doesn't exist returns ErrNotFound.

System.GetReuploadableFile

func (s *System) GetReuploadableFile(fileKey string, preserveName bool) (*File, error)

GetReuploadableFile constructs a new reuploadable File value from the associated fileKey blob.Reader.

If preserveName is false then the returned File.Name will have a new randomly generated suffix, otherwise it will reuse the original one.

This method could be useful in case you want to clone an existing Record file and assign it to a new Record (e.g. in a Record duplicate action).

If you simply want to copy an existing file to a new location you could check the Copy(srcKey, dstKey) method.

System.IsEmptyDir

func (s *System) IsEmptyDir(dir string) bool

Checks if the provided dir prefix doesn't have any files.

A trailing slash will be appended to a non-empty dir string argument to ensure that the checked prefix is a "directory".

Returns "false" in case it has at least one file, otherwise - "true".

System.List

func (s *System) List(prefix string) ([]*blob.ListObject, error)

List returns a flat list with info for all files under the specified prefix.

System.NewWriter

func (s *System) NewWriter(fileKey string, opts *blob.WriterOptions) (*blob.Writer, error)

NewWriter returns a new blob.Writer instance allowing direct file create from an io.Reader value.

If a file with the specified fileKey already exists, it will be replaced.

NB! Make sure to call `Close()` on the resulting writer after you are done working with it.

Note: If you have a bytes slice, filesystem.File, or a multipart header value, you can check also the Upload* related methods as they are more user-friendly.

Example:

content := strings.NewReader("Lorem ipsum dolor sit amet...")

fsys, _ := filesystem.NewLocal("dir")
defer fsys.Close()

w, _ := fsys.NewWriter("example/file/key", nil)
w.ReadFrom(content)
w.Close()

System.OnDelete

func (s *System) OnDelete() *hook.Hook[*DeleteEvent]

OnDelete is a low level hook that is triggered on every System.Delete call.

Note that the hook doesn't fire when a file is being overwritten by a new one, because in that case System.Delete is not invoked.

System.OnNewWriter

func (s *System) OnNewWriter() *hook.Hook[*NewWriterEvent]

OnNewWriter is a low level hook that is triggered on every new writer initialization (aka. when attempting to create a new file with [system.NewWriter] or [system.Upload]).

Note that currently it doesn't trigger on System.Copy but this may change in future releases.

System.Serve

func (s *System) Serve(res http.ResponseWriter, req *http.Request, fileKey string, name string) error

Serve serves the file at fileKey location to an HTTP response.

If the `download` query parameter is used the file will be always served for download no matter of its type (aka. with "Content-Disposition: attachment").

Internally this method uses http.ServeContent so Range requests, If-Match, If-Unmodified-Since, etc. headers are handled transparently.

System.SetContext

func (s *System) SetContext(ctx context.Context)

SetContext assigns the specified context to the current filesystem.

System.Upload

func (s *System) Upload(content []byte, fileKey string) error

Upload writes content into the fileKey location.

System.UploadFile

func (s *System) UploadFile(file *File, fileKey string) error

UploadFile uploads the provided File to the fileKey location.

System.UploadMultipart

func (s *System) UploadMultipart(fh *multipart.FileHeader, fileKey string) error

UploadMultipart uploads the provided multipart file to the fileKey location.