如果值为空,则提交file = type(upload)错误

时间:2015-11-18 06:21:44

标签: javascript php codeigniter

我刚刚意识到网络的弱点,我尝试上传文件时没有直接输入数据,如果没有文件上传,我立即提交是一个错误。

这是我的控制员:

function upload(){
    if ($this->input->post('save')) {
    $fileName = $_FILES['import']['name'];

            $config['upload_path'] = 'C:\files\/';
            $config['file_name'] = $fileName;
            $config['allowed_types'] = 'xls|xlsx|csv|ods|ots';
            $config['max_size']     = 10000;

            $this->load->library('upload');
            $this->upload->initialize($config);

            if(! $this->upload->do_upload('import') )
                $this->upload->display_errors();

            $media = $this->upload->data('import');
            $inputFileName = 'C:\files\/'.$media['file_name'];
        //  Read your Excel workbook
        try {
            $inputFileType = IOFactory::identify($inputFileName);
            $objReader = IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($inputFileName);
        } catch(Exception $e) {
            die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
        };

        //  Get worksheet dimensions
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        //  Loop through each row of the worksheet in turn
        for ($row = 2; $row <= $highestRow; $row++){                        
                    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,NULL,TRUE,FALSE);

我的观点提交

<input type="file" id="import"  size="21" class="file-loading" name="import"  value="<?php echo set_value('import'); ?>"/>

<script type='text/javascript'>
function notEmpty(elem, helperMsg){
    if(elem.value.length == 0){
        alert(helperMsg);
        elem.focus();
        return false;
    }
    return true;
}
</script>

2 个答案:

答案 0 :(得分:1)

控制器

if condition之后添加if ($this->input->post('save')) {
public function upload(){

if ($this->input->post('save')) {

     $fileName = $_FILES['import']['name'];

     if($fileName){ # If $fileName exists

          # And add your rest code here.... 
     }
}
}

答案 1 :(得分:0)

您可以使用如下:

function checkOnSubmit()
{
    if( document.getElementById("import").files.length == 0 ){
        alert('Please upload file');
        return false;
    }
    return true;
}

<form name="myForm" onsubmit="return checkOnSubmit()" method="post">
File: <input type="file" name="import" id="import">
<input type="submit" value="Submit">
</form>

在表单提交或提交按钮的点击事件上调用上述功能。