我使用这个捆绑包通过表单上传文件。这就是我所做的。在我使用捆绑的Twig模板中
<form action="{{ path('guardar-natural') }}" method="POST" class="form-horizontal" role="form" id="registroNatural" {{ form_enctype(form) }}>
{{ form_widget(form.documento_rif) }}
<button type="submit" class="btn btn-primary" id="btnEnviarRegistro">{{ 'registration.submit'|trans }}</button>
</form>
在表单类中:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('documento_rif', 'vich_file', array(
'required' => true,
'mapping' => 'recaudos',
'allow_delete' => true,
'download_link' => true,
'label' => false,
))
->add('usuario', new RegistrationForm());
}
在字段所在的实体中:
use Symfony'Component'HttpFoundation'File'File;
use Vich'UploaderBundle'Mapping'Annotation as Vich;
/**
* @Vich'Uploadable
*/
class Natural
{
/**
* @Vich'UploadableField(mapping="recaudos", fileNameProperty="documentoRIF")
* @var File $imageFile
*/
protected $imageFile;
/**
* @ORM'Column(type="string", length=255, name="documento_rif", nullable=true)
* @var string $documentoRIF
*/
protected $documentoRIF;
/**
* @ORM'Column(type="datetime", nullable=true)
* @var 'DateTime $updatedAt
*/
protected $updatedAt;
/**
* @param File|'Symfony'Component'HttpFoundation'File'UploadedFile $image
*/
public function setImageFile(File $image = null)
{
$this->imageFile = $image;
if ($image) {
$this->updatedAt = new 'DateTime('now');
}
}
/**
* @return File
*/
public function getImageFile()
{
return $this->imageFile;
}
/**
* @param string $documentoRIF
*/
public function setDocumentoRIF($documentoRIF)
{
$this->documentoRIF = $documentoRIF;
}
/**
* @return string
*/
public function getDocumentoRIF()
{
return $this->documentoRIF;
}
}
在config.yml
文件:
vich_uploader:
db_driver: orm # or mongodb or propel or phpcr
storage: vich_uploader.storage.file_system
mappings:
recaudos:
uri_prefix: /recaudos
upload_destination: %kernel.root_dir%/../web/uploads/recaudos
namer: vich_uploader.namer_uniqid
delete_on_update: true
delete_on_remove: true
捆绑包已启用,因为我没有收到任何错误,目录具有正确的权限(0755)。在DB级别,当在documento_rif
列中创建任何记录时,我得到的是字符串/tmp/php1fbjiZ
,而不是文件名,我的代码中有什么问题?
当然,我还有更多关于这一切的代码,但只需在这里写下相关部分。
在表单类型中,应该引用可上传字段(imageFile
),而不是文件名列(documento_rif
)。
未链接到您的错误,但会导致问题:映射中定义的uri_prefix
不正确,应该是/uploads/recaudos
。
剩下的应该没问题。
我前段时间上传了图像表单,这可能会有所帮助:
->add('image', 'file', array(
'label' => 'Image'
))
我用这种方式创建了提交按钮:
->add('submit', 'submit', array(
'label' => 'Upload',
))
处理上传到数据库:
if ($slidersForm->isValid()) {
$data = $slidersForm->getData();
$fileName = $this->uploadFile($data['image']);
$images->setImage($fileName);
$em->persist($images);
$em->flush();
}
上传文件并返回存储在DB:中的文件名的函数
public function uploadFile(UploadedFile $uploadedFile) {
$kernel = $this->get('kernel');
$dir = $kernel->locateResource('@MamgrowMainBundle/Resources/public/images/');
$fileName = $uploadedFile->getClientOriginalName();
$uploadedFile->move($dir, $fileName); //this uploads file to directory $dir you defined
return $fileName;
}
就这样!希望它能以某种方式帮助解决你的问题。