我有一个文件上传功能,我想允许图像和文档并禁止其他图像和文档,检查仅扩展名听起来是个坏主意。
我拥有的代码片段是:
var $actsAs = array(
'MeioUpload' => array(
'file' => array(
'dir' => 'uploads{DS}{ModelName}',
'fields' => array(
'filesize' => 'size',
'mimetype' => array('image/jpeg', 'image/pjpeg', 'image/gif',
'image/png', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation','application/pdf'),
'message' => 'Please upload a valid document file'
),
'allowed_mime' => array('image/jpeg', 'image/pjpeg', 'image/gif',
'image/png', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation','application/pdf'),
'allowed_ext' => array(' .docx',' .jpg',' .jpeg',' .png',' .gif',' .doc',' .xls',' .xlsx',' .pdf'),
'validations' => array(
'MaxSize' => array(
'check' => false,
),
),
'message' => 'Invalid File. Please upload only document or images'
),
),
);
如何分配 mimetype 以允许:仅.txt、.doc、.docx、.xls、.xlsx、.pdf、.png、.jpg、.gif.jpeg
MEIO上传调整会很棒!
在几个地方尝试,最终诉诸核心PHP函数。MeioUpload不支持检查多个MIME类型。希望即将到来的版本中可能会有增强功能。
$allowMime = array('image/jpeg', 'image/pjpeg', 'image/gif',
'image/png', 'application/msword','application/vnd.ms-office','application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation','application/pdf');
$file_info = new finfo(FILEINFO_MIME);
$filename = $attachments[$file_name];
$data = explode(";",$file_info->file($filename));
$mime = $data[0];
if(in_array($mime, $allowMime))
{
//Your code here
可以使用 Mime 类型模型验证。这是代码:
This rule checks for valid mimeType
<?php
public $validate = array('image' => array(
'rule' => array('mimeType', array('image/gif')),
'message' => 'Invalid mime type.'
),
);