php - 何时使用 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?
解决方案
大多数情况下,您应该使用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 类型来确定文件扩展名,而不是从客户端提供的任何元数据中确定文件扩展名。
推荐阅读
- php - 在 PHP 中生成安全的随机密码
- visual-studio-2015 - 如何解决在 Windows 8.1 上安装 Visual Studio 2015 时出现错误“安装程序包丢失或损坏”请帮助我解决此问题
- events - 拖动子元素时触发 Svelte 可拖动,onleave 事件
- node.js - 使用 JWT 在 MERN 堆栈中进行登录身份验证的 POST 请求可能会出现什么问题?
- node.js - 这个正则表达式有什么“不安全”的?
- image - 更新到 Worpdress 5.7 后,预加载器无法正常工作
- mongodb - Kubernetes 有状态的 mongodb:什么是正确的字符串或如何连接到运行有状态集的 istance 的 mongodb,它也附加了服务?
- python - 正则表达式输出有我无法理解的空字符串
- unity3d - 如何使用 unity 2020.3 LTS 下载 Unity dots(实体包)?
- python - 烧瓶 sqlalchemy 更新没有变化