How create a folder / file in Nextcloud with PHP?

Introduction

For a project, we have need to create a file in a folder of Nextcloud with a button in own app.
This file must access by Nextcloud website.

But I don’t find a documentation about that ? Do you have a solution about this ?

Same. The only thing i have found out is the link to this:
https://docs.nextcloud.com/server/latest/developer_manual/basics/storage/filesystem.html#writing-to-a-file

I have followed the procedure based on the tutorial app but i can’t understand when i’m creating a new Apicontroller and call on the AuthorStorage like it should be Php tells me this error
{“Exception”:“OCP\AppFramework\QueryException”,“Message”:"Could not resolve dataStorage!)

dataStorage is the private variable that then gets assigned to AuthorStorage

I think you should take a look at the API https://docs.nextcloud.com/server/19/developer_manual/client_apis/index.html

There might be something missing or outdated in the documentation here. Could you try giving your $storage parameter in the constructor a proper typehint for dependency injection and try the following:

<?php
namespace OCA\MyApp\Storage;

use OCP\Files\IRootFolder;

class AuthorStorage {

    private $storage;

    public function __construct(IRootFolder $rootFolder, $userId){
        $this->storage = $rootFolder->getUserFolder($userId);
    }

    public function writeTxt($content) {
        // check if file exists and write to it if possible
        try {
            try {
                $file = $this->storage->get('/myfile.txt');
            } catch(\OCP\Files\NotFoundException $e) {
                $this->storage->touch('/myfile.txt');
                $file = $this->storage->get('/myfile.txt');
            }

            // the id can be accessed by $file->getId();
            $file->putContent($content);

        } catch(\OCP\Files\NotPermittedException $e) {
            // you have to create this exception by yourself ;)
            throw new StorageException('Cant write to file');
        }
    }
}

I’ll take another look to give that documentation page an update soon.

This actually works, thanks.
Before it wouldn’t and it never gave me any error as to why

in nextclud 21 this exemple don’t work anymore :frowning:

Only touch don’t work, I don’t know why, do you have information ?