如何从 Symfony3 中的文件变量获取路径
How to get path from file variable in Symfony3
我正在使用 Symfony3 开发一个网站,您可以为您的个人资料上传一张图片。但是我想检查图片是否真的是图片,文件是否小于2MB。
输入元素已经有一个 accept='image/*'
属性,所以这只是服务器端的问题。
这是我用来检查图像是否真的小于 2MB 的代码:
if(getimagesize($user->getAvatarFile()) !== false) {
if ($organisation->getAvatarFile()->getSize() > 2000000){
$this->addFlash('error', "Image too large!");
}
} else {
$this->addFlash('error', "File is not an image!");
}
来自用户的 avatarFile
实际上是该文件,但我如何获取它的路径以便我可以使用 getimagesize
?
提前致谢。
你应该查看关于 File (which is the same as Image 的 symfony 文档,mimeType 除外)。
有一些限制,比如maxSize,它们很有用。
use Symfony\Component\Validator\Constraints as Assert;
class User
{
/**
* @Assert\Image(
* maxSize = "2M",
* maxSizeMessage= "The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}."
* )
*/
protected $AvatarFile;
}
编辑:如果你只想获取文件路径,在移动它之前,你可以使用getClientOriginalName函数。请注意,它不会 return 完整的文件路径,因为它可能是预期的,因为在上传时,文件在您的 /tmp 目录中重命名,然后移动(因此,如果需要重命名)。
我正在使用 Symfony3 开发一个网站,您可以为您的个人资料上传一张图片。但是我想检查图片是否真的是图片,文件是否小于2MB。
输入元素已经有一个 accept='image/*'
属性,所以这只是服务器端的问题。
这是我用来检查图像是否真的小于 2MB 的代码:
if(getimagesize($user->getAvatarFile()) !== false) {
if ($organisation->getAvatarFile()->getSize() > 2000000){
$this->addFlash('error', "Image too large!");
}
} else {
$this->addFlash('error', "File is not an image!");
}
来自用户的 avatarFile
实际上是该文件,但我如何获取它的路径以便我可以使用 getimagesize
?
提前致谢。
你应该查看关于 File (which is the same as Image 的 symfony 文档,mimeType 除外)。
有一些限制,比如maxSize,它们很有用。
use Symfony\Component\Validator\Constraints as Assert;
class User
{
/**
* @Assert\Image(
* maxSize = "2M",
* maxSizeMessage= "The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}."
* )
*/
protected $AvatarFile;
}
编辑:如果你只想获取文件路径,在移动它之前,你可以使用getClientOriginalName函数。请注意,它不会 return 完整的文件路径,因为它可能是预期的,因为在上传时,文件在您的 /tmp 目录中重命名,然后移动(因此,如果需要重命名)。