首页 > 解决方案 > 何时使用 Symfony 的 UploadedFileguessClientExtension() 与 guessExtension()?

问题描述

将文件从 ReactJS/Javascript 前端应用程序上传到 Symfony 4 后端,我尝试获取其文件扩展名。

收到文件后,我实例化一个UploadedFile对象,该对象具有以下可用方法:

$uploadedFile->getClientOriginalExtension();
$uploadedFile->getClientMimeType();
$uploadedFile->guessClientExtension();
$uploadedFile->guessExtension();

我希望那些吸气剂能返回一致的结果,但事实并非如此。

上传文件的返回结果为image-ile.jpg

getClientOriginalExtension() -> ''
getClientMimeType()          -> 'application/octet-stream'
guessClientExtension()       -> 'bin'
guessExtension()             -> 'jpeg'
`

Image file is sent using javascript FormData, with `Content-Type: multipart/form-data`:

> ------WebKitFormBoundaryvFjJSluadmvCob6T
Content-Disposition: form-data; name="image-ile.jpg"; filename="image-ile.jpg"
Content-Type: image/jpeg

In my case, the `guessClientExtension()` doesn't return the relevant file extension while the `guessExtension()` does. So in which cases should I use one getter instead of the other one?

标签: phpsymfonyfile-uploadsymfony4

解决方案


大多数情况下,您应该使用guessExtension()over guessClientExtenstion()

后者使用客户端提供的 mime-type 来确定文件的扩展名。但我可以向您发送一个设置 mime-type 的 Word 文件image/jpg,而您将设置不正确的扩展名。

与大多数事情一样,信任客户从来都不是一个很好的做法,除非您有非常具体的理由这样做。

何时使用此值完全取决于应用程序,但在某些情况下,您可能对了解客户端实际发送的元数据感兴趣。没有明确的“何时使用”列表,只是有时需要。我想到了日志记录和调试。

但它的短处是:除非您有特定的用例,否则您guessClientExtension()可能对guessExtension().

如果您检查每个函数的源代码(您可以在自己的 IDE 中完成),您将看到以下注释guessClientExtension()

/**
 * Returns the extension based on the client mime type.
 *
 * If the mime type is unknown, returns null.
 *
 * This method uses the mime type as guessed by getClientMimeType()
 * to guess the file extension. As such, the extension returned
 * by this method cannot be trusted.
 *
 * For a trusted extension, use guessExtension() instead (which guesses
 * the extension based on the guessed mime type for the file).

guessExtension()实际上是在 上定义File,并通过猜测上传的实际文件的 mime 类型来确定文件扩展名,而不是从客户端提供的任何元数据中确定文件扩展名。


推荐阅读