通过BuildTask将图像从外部库添加到SilverStripe站点

时间:2016-02-29 09:34:50

标签: silverstripe

我正在制作Silverstripe构建任务以从外部图库中获取许多图像,并使用必要的数据库链接创建/上传到/assets/images/gallery文件夹中GalleryPage

所以我加载了Urls列表,将图像显示到浏览器,现在如何使用必要的GalleryPage数据库链接将图像保存到assets文件夹中?

class ImportGalleryTask extends BuildTask {
    public function writeImage($data) {
        //$data->Title
        //$data->Filename
        //$data->Url
        //this is the external url that I can output as an image to the browser
        //
        // folder to save image is 'assets/images/gallery'
        //
        // ? save into folder and database and associate to PageImageBelongsToID  ?
    }
}

1 个答案:

答案 0 :(得分:3)

您可以使用copy将远程文件复制到本地文件系统。必须将PHP配置为支持allow_url_fopen

因此,您生成的函数可能如下所示:

/**
 * @param $data
 * @return null|Image return written Image object or `null` if failed
 */
public function writeImage($data) 
{
    // The target folder for the image
    $folder = Folder::find_or_make('images/gallery');

    // assuming that $data->Filename contains just the file-name without path
    $targetPath = $folder->getFullPath() . $data->Filename;

    // Check if an image with this name already exists
    // ATTENTION: This will overwrite existing images! 
    // If you don't want this, you need to implement this differently
    if(
        file_exists($targetPath) &&
        $image = Image::get()->where(array(
            '"Name" = ?' => $data->Filename, 
            '"ParentID" = ?' => $folder->ID
        ))->first()
    ){
        // just copy the new file over…
        copy($data->Url, $targetPath);
        // … and delete all cached images
        $image->deleteFormattedImages();
        // and we're done
        return $image;
    }

    // Try to copy the file
    if (!copy($data->Url, $targetPath)) {
        return null;
    }

    // Write the file to the DB
    $image = Image::create(array(
        'Name' => $data->Filename,
        'ParentID' => $folder->ID,
        'Filename' => $folder->getRelativePath() . $data->Filename
    ));

    $image->write();
    return $image;
}