上传excel文件时的报错:The filetype you are attempting to upload is not allowed

使用php CodeIgniter 框架,在macOS 系统与linux/windows操作系统中使用phpExcel上传excel文件时的报错

问题复原:

在 mac 系统上使用 WPS 创建.xlsx为扩展名的 excel 文件。在本机(mac)中正常上传,但是在 linux/windows 操作系统上传是报错:The filetype you are attempting to upload is not allowed

排查

  1. 把文件上传后的扩展名和 MIME 类型都打印出来,得到的结果是扩展名都是一样的: .xlsx, 却得到了不同的 MIME 类型。
    MAC: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    linux/windows :application/octet-stream; charset=binary
  2. 查看 CI 源码分析
    发现不管那个操作系统都是使用 finfo_open()+finfo_file() 函数作为获取MIME类型的方法。起初怀疑是finfo_open()+finfo_file() 在不同环境下判断可能存在不准确的情况,毕竟除了这种方法获取 MIME 之后还有其他方法,带着这个疑问使用 php 官网推荐的 mime_content_type() 函数测试,失望的是得到了同样的结果。

注:php5.3 废弃了 mime_content_type() 函数的使用,不过在 php5.3+ 之后又开始使用了,而官网不在维护 pecl 扩展包中的 fileinfo 函数。

结论

经测试结果,在 mac 操作系统中创建的 excel 文件,上传后确实会得到不同的 MIME 类型

解决

方法有二

  1. 通过 CI 上传文件的配置项取消MIME的检测【推荐】
    $this->upload->detect_mime = FALSE;
  2. 补充 config/mimes.php 中扩展名xlsx中对应的 mime 类型数组
    'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'application/vnd.ms-excel', 'application/msword', 'application/x-zip', 'application/octet-stream')

你可能感兴趣的:(上传excel文件时的报错:The filetype you are attempting to upload is not allowed)