判断上传文件后缀名和压缩文件上传

看到这个上传压缩代码,记录一下:

public function search()
{
    if (!$this->validate()) {
        return $this->getErrorResponse();
    }
    set_time_limit(0);
    $filename = $_FILES['excel']['name'];
    $tmpname = $_FILES['excel']['tmp_name'];
    $path = \Yii::$app->basePath . '/web/temp/';
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));   //这个方法判断上传的文件的后缀
    if (($ext != 'xlsx') && ($ext != 'xls')) {
        return [
            'code' => 1,
            'msg' => '请上传excel文件'
        ];
    }
    $file = time() . $this->store_id . '.' . $ext;
    $uploadfile = $path . $file;
    $result = move_uploaded_file($tmpname, $uploadfile);          //移除临时文件 
    // 加载zip  
    $imagePath = \Yii::$app->basePath . '/web/uploads/image/tbi/' . date('Y') . '/' . date('m') . '/';
    try {
        $this->get_zip_originalsize($_FILES['zip']['tmp_name'], $imagePath); //压缩文件上传
    } catch (\Exception $e) {
        unlink($uploadfile);
        return [
            'code' => 1,
            'msg' => $e->getMessage()
        ];
    }

    // 读取Excel文件
    $reader = \PHPExcel_IOFactory::createReader(($ext == 'xls' ? 'Excel5' : 'Excel2007'));
    $excel = $reader->load($uploadfile);
    $sheet = $excel->getActiveSheet();
    $highestRow = $sheet->getHighestRow();
    $highestColumn = $sheet->getHighestColumn();
    $highestColumnCount = \PHPExcel_Cell::columnIndexFromString($highestColumn);
    $row = 1;
    $colIndex = [];
    $arr = [];
    while ($row <= $highestRow) {
        $rowValue = array();
        $col = 0;
        while ($col < $highestColumnCount) {
            $rowValue[] = (string)$sheet->getCellByColumnAndRow($col, $row)->getValue();
            ++$col;
        }
        if(count($rowValue) == 0){
            unlink($uploadfile);
            return [
                'code' => 1,
                'msg' => '上传文件内容不符合规范'
            ];
        }else{
            if($row == 1){

            }else if($row == 2){
                $colIndex = array_flip($rowValue);
            }else if($row == 3){
            }else{
                $newItem = [
                    'title' => $rowValue[$colIndex['title']],
                    'price' => $rowValue[$colIndex['price']],
                    'num' => $rowValue[$colIndex['num']],
                    'description' => $rowValue[$colIndex['description']],
                    'cat_id' => $rowValue[$colIndex['cat_id']],
                    'drug_type' => $rowValue[$colIndex['drug_type']],
                    'goods_no' => $rowValue[$colIndex['goods_no']],
                ];
                $picContents = $rowValue[$colIndex['picture']];
                $allpics = explode(';', $picContents);
                $pics = array();
                $optionpics = array();

                foreach ($allpics as $imgurl) {
                    if (empty($imgurl)) {
                        continue;
                    }

                    $picDetail = explode('|', $imgurl);
                    $picDetail = explode(':', $picDetail[0]);
                    $imgRootUrl = str_replace('http://', 'https://', \Yii::$app->request->hostInfo . \Yii::$app->request->baseUrl . '/uploads/image/tbi/' . date('Y') . '/' . date('m') . '/' . $picDetail[0] . '.png');
                    $imgurl = $imagePath . $picDetail[0] . '.png';
                    if (@fopen($imgurl, 'r')) {
                        if ($picDetail[1] == 1) {
                            $pics[] = $imgRootUrl;
                        }

                        if ($picDetail[1] == 2) {
                            $optionpics[$picDetail[0]] = $imgRootUrl;
                        }
                    }
                }

                $newItem['pics'] = $pics;
                $res = $this->save($newItem);
                if($res){
                    $arr[] = $res;
                }
            }
        }
        ++$row;
    }
    $count = count($arr);
    unlink($uploadfile);
    return [
        'code' => 0,
        'msg' => "共导入{$count}条数据"
    ];
}



// 获取字旁文件的内容
private function get_zip_originalsize($filename, $path)
{
    if (!file_exists($filename)) {
        throw new \Exception('文件不存在', 1);
    }

    $filename = iconv('utf-8', 'gb2312', $filename);
    $path = iconv('utf-8', 'gb2312', $path);
    $resource = zip_open($filename);

    while ($dir_resource = zip_read($resource)) {
        if (zip_entry_open($resource, $dir_resource)) {
            $file_name = $path . zip_entry_name($dir_resource);
            $file_path = substr($file_name, 0, strrpos($file_name, '/'));

            if (!is_dir($file_path)) {
                mkdir($file_path, 511, true);
            }

            if (!is_dir($file_name)) {
                $file_size = zip_entry_filesize($dir_resource);

                if ($file_size < 1024 * 1024 * 10) {
                    $file_content = zip_entry_read($dir_resource, $file_size);
                    $ext = strrchr($file_name, '.');

                    if ($ext == '.png') {
                        file_put_contents($file_name, $file_content);
                    } else {
                        if ($ext == '.tbi') {
                            $file_name = substr($file_name, 0, strlen($file_name) - 4);
                            file_put_contents($file_name . '.png', $file_content);
                        }
                    }
                }
            }

            zip_entry_close($dir_resource);
        }
    }

    zip_close($resource);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值