Programatically upload files with template, and update `files` field with these files

I have a folder full of images that:

  • I have to upload to a series of pages of work type
  • Using image file template
  • And assign them to a files field, titled cover.

Each page has one cover field, with a single image from the batch.

How do I programatically do this? Do I have to separate the upload file and update field code?

If there are docs for this, please help me find them

Thanks

These two are quite similar and should help you get going:

Also this recipe: Uploading files from frontend | Kirby CMS

1 Like

@texnixe I am getting a strange exception: The method: "alt" does not exist with this code:

        ...
        $img =  asset('assets/import/img/' . $path . '.jpg');

        if ($img->exists()) {
            echo 'file ' . $img->filename() . ' exists, proceed to upload<br />';
            try {
                $w->createFile([
                    'source'   => $img,
                    'filename' => $img->filename(),
                    'template' => 'focusimg',
                ]);
                echo 'success <br />';
            } catch (Exception $e) {
                echo $e->getMessage() . '<br />';
            }
            
        } else {
            "file does not exist <br /><br />";
        }

It seems the exception is thrown when reaching the 'template' => 'focusimg' line.

That blueprint looks like this:

title: focus image
accept: image/*

fields:
  alt:
    label: Texto alternativo
    type: text 
    width: 1/1
  focus:
    label: Centro del recorte
    type: focus
    width: 1/2

Is it requiring me to fill the alt field using a content array on the createFile method? and if yes, why, if that is not a required field? or that is just a name coincidence between some internal alt and my alt field?

Thanks

It seems my mistake was to use asset() to create the source, instead of simply providing the path as a string, this works:

        $img =  'assets/import/img/' . $path . '.jpg';

        if (file_exists($img)) {
            echo 'file ' . $img . ' exists, proceed to upload<br />';
            try {
                $w->createFile([
                    'source'   => $img,
                    'filename' => $path . '.jpg',
                    'template' => 'focusimg',
                ]);
                echo 'success <br />';
            } catch (Exception $e) {
                echo $e->getMessage() . '<br />';
            }
            
        } else {
            "file does not exist <br /><br />";
        }