Silverstripe Image Upload 正在更改名称

Silverstripe Image Upload is changing name

我正在上传图像并在存储图像时将文件名设置为 'assets/Uploads/54f092af271b9.png' 但在保存后,文件名字段丢失了一部分。它变成 'assets/54f092af271b9.png' 完全失去 "Uploads/" 目录。它应该发生吗?

代码如下:

            <?php 
            $img = new Image();
            $baseName = pathinfo($file, PATHINFO_BASENAME);
            $fileName = 'assets/Uploads/' . $baseName;

            var_dump($fileName);

            $img->Name = $baseName;
            $img->Filename = $fileName;
            $img->OwnerID = ($memberID = Member::currentUserID()) ? $memberID : 0;
            $img->write();


            var_dump($img->Filename); exit;

输出为:

assets/Uploads/54f092af271b9.png assets/54f092af271b9.png'

有什么想法吗?

我能够使用您提供的代码重现该问题。经过一番挖掘后,这是我的发现。

一切都从 onAfterWrite function in File class (which Image extends). Fired after you called write (obviously), this calls updateFilesystem where this line sets the Filename property with the result of the getRelativePath 函数调用开始。

在撰写本文时,getRelativePath 看起来像这样:

public function getRelativePath() {
    if($this->ParentID) {
        // Don't use the cache, the parent has just been changed
        $p = DataObject::get_by_id('Folder', $this->ParentID, false);
        if($p && $p->exists()) return $p->getRelativePath() . $this->getField("Name");
        else return ASSETS_DIR . "/" . $this->getField("Name");
    } else if($this->getField("Name")) {
        return ASSETS_DIR . "/" . $this->getField("Name");
    } else {
        return ASSETS_DIR;
    }
}

查看该代码,您遇到的问题是 ParentID 在将其写入数据库时​​未在记录中设置,因此第二个条件是 运行 而不是 return正在处理 ASSETS_DIR . "/" . $this->getField("Name").

的结果

这就是问题所在,现在寻求解决方案。 Silverstripe 想要一个父文件夹,您只需给它一个。

幸运的是 Folder class called find_or_make 上有一个很棒的小功能,它的功能如其名,要么在文件系统和数据库中找到文件夹记录,要么为您生成它。

注意:在我自己的测试中,虽然我有一个 "Uploads" 文件夹,但我没有相应的数据库记录,所以这个函数为我写了一个 returned结果。

然后我使用结果将我正在写入数据库的图像赋予 ParentID 并且它使第二个 var_dump return 与第一个具有相同的值。

这就是您在调用 write 之前需要添加到代码中的全部内容:

$parentFolder = Folder::find_or_make('Uploads');
$img->setParentID($parentFolder->ID);