1. List of acceptable file extensions for upload: ogg, pdf, xml, zip, gz, mp4, mp3, wav, webm, gif, jpeg, jpg, png, webp, svg, svgz, tiff, css, csv, txt, vcf, vcard, mov, qt, mkv, mk3d, mka, mks, wmv, flv, doc, docx, xls, xlsx, ppt, pptx
2. Uploading a file with the extension .jpg failed with the message: not allowed, as shown in Figure 1

{
"code": 226004,
"message": "数据验证失败:只允许使用以下文件扩展名的文件:ogg, pdf, xml, zip, gz, mp4, mp3, wav, webm, gif, jpeg, jpg, png, webp, svg, svgz, tiff, css, csv, txt, vcf, vcard, mov, qt, mkv, mk3d, mka, mks, wmv, flv, doc, docx, xls, xlsx, ppt, pptx。"
}
3. Assign the array of UploadedFile instances to Upload::files and print it out
Array
(
[0] => yii\web\UploadedFile Object
(
[name] => 20191204113827.jpg
[tempName] => E:\phpuploadtmp\php6053.tmp
[type] => image/jpeg
[size] => 1970110
[error] => 0
)
)
4. Edit the file: /common/components/validators/FileValidator.php, and modify the method: validateExtension($file) to enable debugging. Request again, and the output is: 2
/**
* Checks if given uploaded file have correct type (extension) according current validator settings.
* @param UploadedFile $file
* @return bool
* @throws InvalidConfigException when the `fileinfo` PHP extension is not installed and `$checkExtension` is `false`.
*/
protected function validateExtension($file)
{
$extension = mb_strtolower($file->extension, 'UTF-8');
if ($this->checkExtensionByMimeType) {
$mimeType = FileHelper::getMimeType($file->tempName, null, false);
if ($mimeType === null) {
echo 1;
exit;
return false;
}
$extensionsByMimeType = FileHelper::getExtensionsByMimeType($mimeType);
if (!in_array($extension, $extensionsByMimeType, true)) {
// MS Office 2007 扩展(docx、xlsx),其 MIME 类型为 application/zip 的特殊处理
$msMimeTypes = ['application/zip'];
$msExtensions = ['docx', 'xlsx'];
if (!(in_array($mimeType, $msMimeTypes) && in_array($extension, $msExtensions)))
{
echo 2;
exit;
return false;
}
}
}
if (!in_array($extension, $this->extensions, true)) {
echo 3;
exit;
return false;
}
return true;
}
5. checkExtensionByMimeType: Whether to determine the file extension by the file’s MIME type. If the file extension determined by the MIME type does not match the given file’s extension, the file will be considered invalid. It defaults to true, meaning this check is performed. Print the values of $mimeType, $extensionsByMimeType, and $extension in sequence; their values are respectively: as shown in Figure 2

image/png
Array
(
[0] => png
)
jpg
6. Analyzing the results, because $extensionsByMimeType and $extension do not match, the upload is not allowed. This is expected behavior. After changing the file extension to png, the upload succeeds, as shown in Figure 3

{
"code": 10000,
"message": "上传资源成功",
"data": {
"items": [
{
"original_file_name": "20191204113827 .png",
"relative_path": "/tmp/2020/01/21/1579571397.5836.1739899586.png",
"url": "http://127.0.0.1/pcs-api/storage/tmp/2020/01/21/1579571397.5836.1739899586.png"
}
]
}
}
