![](/img/trans.png)
[英]Symfony2 + SonataAdmin + VichUploaderBundle - Image Upload Field
[英]Symfony3 + VichUploaderBundle + custom upload directory
我已經用自定義文件名設置了 VichUploaderBundle,它工作正常..
我的相關 config.yml:
vich_uploader:
db_driver: orm
mappings:
product_image:
uri_prefix: '/uploads/products'
upload_destination: '%kernel.root_dir%/../web/uploads/products'
namer: namer.product_image
#namer: vich_uploader.namer_uniqid
#namer: vich_uploader.namer_origname
#namer: vich_uploader.namer_property
inject_on_load: false
delete_on_update: true
delete_on_remove: true
我的自定義名稱:
public function name($obj, PropertyMapping $mapping)
{
$file = $mapping->getFile($obj);
$new_name = $this->generateRandomSecret();
if ($extension = $file->guessExtension())
{
$new_name = $new_name .'.'. $extension;
}
return $new_name;
}
但是,我想使用自定義路徑上傳文件。
我將所需的上傳路徑保存到控制器中的會話變量“upload_files_path”,並在命名器中檢索所述路徑。
它保存到數據庫(id、image_name、udated_at),但不將文件寫入文件系統!
當我打電話
<img src="{{ vich_uploader_asset(product, 'imageFile') }}" />
在模板中,它返回以“/”開頭的文件路徑。 我不知道如何使它工作。
這是我對自定義文件路徑的配置:所以我將“uri_prefix”和“upload_destination”編輯為空白。 已編輯的 config.yml
vich_uploader:
db_driver: orm
mappings:
product_image:
uri_prefix: ''
upload_destination: ''
namer: namer.product_image
inject_on_load: false
delete_on_update: true
delete_on_remove: true
我更新的自定義名稱:在這里我將上傳路徑與新文件名連接起來。
public function name($obj, PropertyMapping $mapping)
{
$file = $mapping->getFile($obj);
$new_name = $this->generateRandomSecret();
if ($extension = $file->guessExtension())
{
$new_name = $new_name .'.'. $extension;
}
$upload_path = $this->container->get('session')->get('upload_files_path');
$full_path = $upload_path . $new_name;
return $full_path;
}
感謝您的時間和知識。
不要在命名器中使用會話,因為命名器必須是無狀態的。 要自定義目錄,您可以使用目錄名稱。 請參閱https://github.com/dustin10/VichUploaderBundle/blob/master/docs/namers.md#directory-namer 上的文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.