php - 具有规则扩展名的 Codeigniter 4 验证上传文件无法按预期工作
问题描述
我有一个导入功能,这是我的代码
public function import($id = NULL)
{
if ($this->request->getMethod() == 'post') {
if (empty($id) && $id != '0') {
$rules = [
'template' => [
'label' => 'Template',
'rules' => 'uploaded[template]|ext_in[template,xlsx]'
]
];
if (!$this->validate($rules)) {
return $this->respond([
'type' => 'failed',
'message' => $this->validator->getError("template")
]);
}
if ($file = $this->request->getFile('template')) {
if ($file->isValid() && !$file->hasMoved()) {
$newName = $file->getRandomName();
$file->move(WRITEPATH . "cache", $newName);
try {
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load(WRITEPATH . "cache" . DIRECTORY_SEPARATOR . $newName);
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
if (count($sheetData) < 2) {
throw new \Exception("Unable to import empty files");
}
return $this->respond([
'type' => 'success',
'token' => $newName,
'rows' => count($sheetData) - 1
]);
} catch (\Exception $e) {
return $this->respond([
'type' => 'failed',
'message' => $e->getMessage()
]);
}
}
}
} else {
$token = $this->request->getPost('token');
$last = $this->request->getPost('last');
$filePath = WRITEPATH . "cache" . DIRECTORY_SEPARATOR . $token;
if (!$this->model->importExcel($filePath, $id)) {
return $this->respond([
'type' => 'failed',
'message' => 'Failed to import kpi',
]);
}
if ($last == '1' && file_exists($filePath)) {
unlink($filePath);
}
return $this->respond([
'type' => 'success',
'message' => 'The kpi were imported successfully',
]);
}
}
$data = [
'formAction' => base_url("scorecard-tbcci/reporting/master-kpi/import"),
'formMethod' => 'POST',
];
echo view('ScorecardTbcci\Views\Reporting\Kpis\ImportFormView', $data);
}
问题是,当我上传xlsx文件时。此文件未通过验证。将出现错误警告“上传没有有效的文件扩展名”。所以我尝试使用xls文件,我也更改了规则,但它相同。当我用csv更改规则并上传 csv 文件时。它通过了验证。我不知道有什么问题。谁能帮我 ?
解决方案
上传 xlsx 文件时执行 dd($_FILES) 并检查相应的 mime 类型。
然后将其与您的 app/config/mimes.php 进行比较,并检查该 mime 类型是否存在于 xlsx 数组中。您上传的文件可能具有配置文件中不存在的 mime 类型。
推荐阅读
- php - 如何检查用户是否有过去 1 小时的 X 条记录?[PHP/MySQL]
- openshift - `oc cluster up` 时的问题
- c# - 如何为异常端点 api 配置设置路由?
- java - 怎么处理用硒掩盖其他元素,检查其他答案没有任何帮助
- mariadb - 具有空值的 Mariadb 查询变量不返回任何内容
- javascript - 用于处理错误嵌套标签的 HTML“采用代理”算法的实现
- javascript - 如何仅使用 Jquery 在页面加载之前隐藏 div
- css - 将链接包裹在图像周围会破坏 flexbox 布局并导致浏览器呈现怪癖
- haskell - 如何在 Haskell 中修复“错误:在输入 '=' 上解析错误”
- qt - GStreamer / QML 应用程序中的多个 4K 视频 = 黑色闪烁