/**
* @ORM'PrePersist()
* @ORM'PreUpdate()
*/
public function preUpload()
{
if (null !== $this->file) {
$this->path = $this->file->guessExtension();
}
}
/**
* @ORM'PostPersist()
* @ORM'PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
return;
}
// you must throw an exception here if the file cannot be moved
// so that the entity is not persisted to the database
// which the UploadedFile move() method does
$this->file->move($this->getUploadRootDir(), $this->id.'.'.$this->file->guessExtension());
unset($this->file);
}
/**
* @ORM'PostRemove()
*/
public function removeUpload()
{
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
public function getAbsolutePath()
{
return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->id.'.'.$this->path;
}
嗨,在这个 cose 我上传文件 当我将文件名 ID 保存到目录中时,一切都有效,但仅保存到数据库中保存 JPG...没有身份证
在预
持久生命周期回调中,尚未为您的实体分配 ID,因此$this->id.'.'.$this->file->guessExtension()
调用此 ID 时,$this->id
将被null
您已正确遵循说明书中的示例。它只是没有提到存储在 path 下的数据库中的唯一内容是扩展名。这并不重要,因为文件名将始终是与扩展名连接的 id。即 $filename = $this->id . $this->path
因此,如果您希望存储在路径下的字符串准确表示文件名,则必须考虑不同的命名策略。
在 preUpload 方法中,只需将扩展文件影响到 path 属性。因此,在您的数据库中,您只有jpg扩展名是正常的。
编辑:在您的preUpload方法中,ID尚未受到ORM的影响,因此您不能使用它来生成文件名。IMO,您应该使用 uniquid 生成唯一的文件名。类似$this->path = uniquid().'.'.$this->file->guessExtension()
好的,
我曾经遇到过同样的问题(只有.txt(。
我认为如果您的文件名中有特殊的字符,这可能是一个问题。
我是这样解决的:
$filepath = $this->file->getClientOriginalName();
$filepath = str_replace(array('/', ' ', '-', 'ä', 'ö', 'ü', 'Ä', 'Ö', 'Ü', 'ß'), array('_', '_', '', 'ae', 'oe', 'ue', 'Ae', 'Oe', 'Ue', 'ss'), $filepath);
$this->path = $filepath;
希望这是您问题的答案,如果无论如何还没有解决:D