1、可接受上传的文件扩展名列表: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、上传扩展名为:.jpg 的文件,上传失败,提示:不允许,如图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、将 UploadedFile 实例数组赋值给 Upload::files,打印出来
Array ( [0] => yii/web/UploadedFile Object ( [name] => 20191204113827.jpg [tempName] => E:/phpuploadtmp/php6053.tmp [type] => image/jpeg [size] => 1970110 [error] => 0 ) )
4、编辑文件:/common/components/validators/FileValidator.php,修改方法:validateExtension($file),以启动调试,再次请求,输出: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:是否通过文件的 MIME 类型来判断其文件扩展。若由 MIME 判定的文件扩展与给定文件的扩展不一样,则文件会被认为无效。默认为 true,代表执行上述检测。依次打印输出:$mimeType、$extensionsByMimeType、$extension,其值分别为:如图2
image/png Array ( [0] => png ) jpg
6、分析结果,由于:$extensionsByMimeType、$extension 不匹配,因此,不允许上传,是正常的,将其扩展名修改为 png,上传成功,如图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" } ] } }
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/181483.html