SilverStripe 4 - файл не загружен / база данных записана через AJAX - PullRequest
0 голосов
/ 21 мая 2018

как сообщается здесь , я застрял в проблеме, связанной с файлами, загруженными в CMS по запросу ajax.По сути, я получил интерфейсную форму, которая должна отправлять файлы через ajax-вызовы на контроллер страницы.Файлы должны быть сохранены и связаны с Member/DataExtension, который реализует свойство / отношение File::class/$many_many (чтобы сохранить и связать их с каждым пользователем CMS).

Вот мой подход:

My Member Extension

[...]
/**
 * Classe Utente - Estensione
 */
class UtenteExtension extends DataExtension
{
    // Dichiarazione Proprietà
    private static $many_many = [
        'AllegatiUpload' => File::class, // this field should save users file uploads
        [...]
    ];
    private static $owns = [
        'AllegatiUpload',
        [...]
    ];
[...]

Включено Controller:

use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\ErrorPage;
use SilverStripe\Assets\Folder;
use SilverStripe\Assets\File;
use SilverStripe\Assets\Upload;
use SilverStripe\Security;
use SilverStripe\Security\Group;
use SilverStripe\Assets\Storage\AssetStore;

/**
 * Classe Controller Utente - Dashboard
 */
class UtenteDashboardController extends PageController
{
    // Dichiarazione Proprietà
    private static $allowed_actions = [
        'carica'
    ];

    /**
    * Funzione gestione validazione ed invio form caricamento
    * @param  HTTPRequest $request Richiesta HTTP
    * @return HTTPResponse Risposta HTTP
    */
    public function carica(SS_HTTPRequest $request) {
        if (!$request->isAjax()) {
            return ErrorPage::response_for(404);
        } else if (!$request->isPOST()) {
            return $this->httpError(400, 'Metodo POST richiesto');
        } else {
            $documento = $request->postVar('documento'); // File data sent by FormData JS API

            if (!isset($documento)) {
                return $this->httpError(500, 'Dati richiesti mancanti');
            } else {
                // User check
                $utente = Security::getCurrentUser();

                if ($utente->inGroup(Group::get()->filter('Code', 'clienti')->first()->ID)) {
                    // File uploading
                    $cartellaUpload = 'clienti/'. strtolower($utente->Surname) .'/uploads';

                    Folder::find_or_make($cartellaUpload);

                    // I tried with the official guide approach, with this line - with no results
                    //$utente->AllegatiUpload()->setFromLocalFile($cartellaUpload, documento, AssetStore::CONFLICT_OVERWRITE);
                     // Then I tried with this approach
                    $file = File::create();
                    $upload = Upload::create();

                    $upload->loadIntoFile($documento, $file, $cartellaUpload);

                    // Upload check
                    if ($upload->isError()) {
                        return $this->httpError(400, 'Errore di caricamento file');
                    } else {
                        // Relate the file to the destinaion user field
                        $utente->{'AllegatiUpload.ID'} = $upload->getFile()->ID;
                        // Update user
                        $utente->write(); 

                        return new HTTPResponse;
                    }
                } else {
                    return $this->httpError(401, 'Utente non abilitato');
                }
            }
        }
    }
}

Это приводит к тому, что таблица файлов БД не записывается, а также не загружается файл в предназначенном assets месте назначенияпапка.Более того, исключений не выдается - он возвращает HTTPResponse, поэтому я предполагаю, что код beign выполняется без ошибок ?.В любом случае вот результат запроса:

Headers Payload

В настоящее время я не понимаю, что я 'm здесь отсутствует.

Может кто-нибудь помочь мне поймать ошибку?

Заранее спасибо.

1 Ответ

0 голосов
/ 23 мая 2018

Кажется, что моя проблема была связана с ошибочно введенной зависимостью:

use SilverStripe\Security;

Изменив ее так, чтобы она указала на правильный контроллер:

use SilverStripe\Security\Security;

файлы начинают выравниваться, загружаются какожидается.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...