SilverStripe 4 - 将上传的文件保存为成员扩展属性

时间:2018-05-23 07:13:41

标签: php silverstripe silverstripe-4

我试图通过AJAX请求将上传的文件保存到页面控制器,作为Member扩展属性。

我得到了一个Member DataExtension,它实现了一个File属性,其关系为many_many,如下所示:

我的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');
                }
            }
        }
    }
}

我在这个过程中陷入困境,以便将文件与正确的Member配对。我想我错过了正确的语法,因为我正在使用many_many关系而且这个不适合它:

// Relate the file to the destinaion user field
utente->{'AllegatiUpload.ID'} = $upload->getFile()->ID;

我也尝试过这样的方法:

$allegato = $utente->AllegatiUpload();

$allegato->setField('Documento', $upload->getFile()->ID);
$allegato->write();

但是我收到了这个例外:

  

[紧急]未捕获BadMethodCallException:Object-> __ call():方法' write'在' SilverStripe \ ORM \ ManyManyList'

上不存在

也许我必须首先将AllegatiUpload转换为DataObject,然后在其中添加File属性以避免这种情况?

1 个答案:

答案 0 :(得分:0)

在您的情况下,您可以使用$Temp1 = (Import-csv "C:\path\APPcsv.csv" -header "APP") | Select-Object -ExpandProperty APP $Temp2 = (Import-csv "C:\path\ALLdb42APPs.csv"-header "NA1", "NA2", "Applications", "NA3", "Project") | Select-Object -ExpandProperty Project $LargestIndex = [math]::Max($temp1.count,$temp2.count) $CombinedArray = For ($i=0; $i -le $LargestIndex; $i++) { [pscustomobject]@{ APP = $temp1[$i] Project = $temp2[$i] } } $CombinedArray | Export-Csv -Path "C:\path\Example.csv" -NoTypeInformation 语法向关系添加新项:

$object->RelationName()->add($item)

参考https://docs.silverstripe.org/en/4/developer_guides/model/relations/#adding-relations