上传文件处理的UploadForm.php
<?php
namespace common\models;
use yii\base\Model;
use common\helpers\CommonFun;
class UploadForm extends Model
{
const UPLOAD_FILE = 'file';//上传文件
const UPLOAD_IMAGE = 'image';//上传图片
public $inputFile;
public $imageFile;
public function scenarios()
{
return [
self::UPLOAD_FILE => ['inputFile'],
self::UPLOAD_IMAGE => ['imageFile'],
];
}
public function rules()
{
return [
[
['inputFile'],
'file',
'skipOnEmpty' => false,
'extensions' => ['txt', 'zip', 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', '7z', 'gz'],
'on' => 'file'
],
[
['imageFile'],
'image',
'skipOnEmpty' => false,
'extensions' => 'png, jpg, gif, jpeg',
'on' => 'image'
],
];
}
/**
* upload file
* @author
* @dateTime 2017-05-04T19:28:13+0800
* @param string $target the upload directory
* @param string $fileName the uploaded file name
* @return mix
*/
public function upload($target = NULL,$fileName = NULL)
{
if ($this->validate()) {
//$target = $target ? $target : Yii::getAlias('@uploads') . '/'. date("Ym");
if ($this->inputFile != NULL) {
$extension = $this->inputFile->extension;
} else {
$extension = $this->imageFile->extension;
}
$target = $target ? $target : $this->setDefaultUploadDir($extension);
$dir = getcwd() . '/' . $target;
if(!file_exists($target)) {
CommonFun::recursionMkDir($target);
}
$fileName = $fileName ? $fileName : CommonFun::createUniqueStr();
$saveName = $dir . '/' . $fileName . '.' . $extension;
if($this->inputFile != NULL) {
$this->inputFile->saveAs($saveName);
} else {
$this->imageFile->saveAs($saveName);
}
$resultUrl = $target . '/' . $fileName . '.' . $extension;
return $resultUrl;
} else {
return false;
}
}
/**
* 设置默认的上传目录
* 根据各个应用生成目录
* @author
* @dateTime 2017-05-24T09:21:38+0800
* @return string 上传路径
*/
public function setDefaultUploadDir($extension = NULL)
{
$uploadDir = "uploads/" . date("Ym");
if ($extension) {
$uploadDir .= '/'. $extension;
}
if(!file_exists($uploadDir)) {
CommonFun::recursionMkDir($uploadDir);
}
return $uploadDir;
}
}
上传文件为test.xlsx
wps版的mimeType为application/octet-stream
office版的mimeType为application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
yii的验证机制是根据上传文件的mimeType来匹配对应的extension列表,然而xlsx已经被使用了,我不能再加个xlsx的键值对
在不改源码的基础上怎么让wps文件通过FileValidator的验证
按照你的思路应该动这块吧
??????????
我做Excel的时候也发现了这个问题,后来我把验证规则MimeType验证关闭了.
后来自己根据文件类型写了个验证规则
这是我的验证规则
这是我抓的我mime,自己简单写了个方法,虽然受限制,但是对我项目实用
源码是这么对应的