File 限制CakePHP文件输入中的文件类型

File 限制CakePHP文件输入中的文件类型,file,cakephp,upload,mime,file-type,File,Cakephp,Upload,Mime,File Type,我只是想知道是否有办法限制文件输入对话框只显示某些类型的文件。我的网页只能接受.bin或.gz文件类型,但用户可以选择其他文件类型并尝试上载它们 防止上传错误类型的文件的最佳方法是什么 这是我的文件上传控制器: public function uploadFile() { $this->Session->write('isFileUpload', false); $this->Session->write('isFileLa

我只是想知道是否有办法限制文件输入对话框只显示某些类型的文件。我的网页只能接受.bin或.gz文件类型,但用户可以选择其他文件类型并尝试上载它们

防止上传错误类型的文件的最佳方法是什么

这是我的文件上传控制器:

    public function uploadFile()
    {
        $this->Session->write('isFileUpload', false);
        $this->Session->write('isFileLarge', false);

        if($this->request->is('post'))
        {
            $uploadedFile = array();

            // Check if the Document object is set
            // If it is set, process the file for uploading,
            if(isset($this->request->data['Document']))
            {
                $filename = $this->request->data['Document']['MyFile']['tmp_name'];

                $uploadedFile['MyFile']['name'] = $this->request->data['Document']['MyFile']['name'];
                $uploadedFile['MyFile']['type'] = $this->request->data['Document']['MyFile']['type'];
                $uploadedFile['MyFile']['size'] = $this->request->data['Document']['MyFile']['size'];

                // Move the file to the /home/spectracom folder
                $filePath = DS . 'home' . DS . $uploadedFile['MyFile']['name'];

                if (move_uploaded_file($filename, $filePath))
                {
                    $this->Session->write('isFileUpload', true);
                    $this->Session->write('isFileLarge', false);
                    $this->redirect('/tools/upgradebackup');
                }
                else
                {
                    $this->Session->write('isFileUpload', false);
                    $this->Session->write('isFileLarge', true);
                    $this->redirect('/tools/upgradebackup');
                }
            }
            else
            {
                $this->Session->write('isFileUpload', false);
                $this->Session->write('isFileLarge', true);
                $this->redirect('/tools/upgradebackup');
            }
        }
    }
我基本上检查文件是否存在,或者它是否太大,当它返回到主升级页面时,它会设置会话变量


谢谢

您可以限制浏览器允许用户使用在文件选择对话框中选择的内容,尽管并非所有浏览器都支持它

我认为这应该适用于创建输入(您需要使用MIME类型来查看哪些有效):

echo$this->Form->input('MyFile',array('type'=>'file','options'=>array('accept'=>'application/gzip,application/gzip,application/octet stream'))

您还应该在文件到达服务器后通过设置(查看
extension
mimeType
验证规则)对其进行验证


用户选择文件扩展名后,还可以使用JavaScript验证文件扩展名,如果文件扩展名错误,则清除文件输入字段。

使用Cakephp 3.4测试

$this->Form->control('my_file', ['label' => 'Upload File','type' => 'file', 'accept' => 'application/msword']);

我也遇到过这种情况。我在服务器端进行验证,检查文件类型是否正确。但我也想知道如何限制它的客户端。我只是希望人们只能看到某些文件类型。我只是在做了一些快速的研究后更新了答案。在可用的地方使用accept属性,然后使用JS和模型验证。谢谢。您知道如何将accept合并到这个中吗<代码>echo$this->Form->input('MyFile',数组('type'=>'file')我认为列表文件类型会有帮助:还不起作用。我用CakePHP2.5.7尝试了上面的代码片段,但没有成功。让我们看看html源代码呈现的代码片段。