PHP文件上传数据存入数据库
来源:互联网 发布:51单片机烧录器 编辑:程序博客网 时间:2024/05/20 03:47
此处是客户端的核心代码:
<body><div id="container"><div id="left"><div id="title"><p>文件导入</p></div><div id="body"><form id = "upfile" action="php/upLoadFile.php?p=0" method="post" enctype="multipart/form-data"><span style="font-size: 20px;">选择正确的文件:</span><input type="hidden" value="1000000" name = "MAX_FILE_SIZE"><input type="file" id = "upfile" name = "file" value="" ><br><br><br><br><input type="submit" value="上传"></form></div></div><div id="middle"><hr style="width: 2px;height:100%"></div><div id="right"><div id="title"><p>文件模板下载</p></div><div id="body"><form action="get"><a href ="php/doDownload.php?filename=../data/list.xlsx" style="font-size: 20px;">文件模板下载</a><img src="images/file.png" alt="图片" style="width:20px;"><br><img src="images/demo.png" alt="图片"></form></div></div></div></body>
此处是服务器端代码:
<?phprequire_once("fileupload.class.php");require_once 'Classes/PHPExcel.php';require_once 'Classes/PHPExcel/IOFactory.php';require_once 'Classes/PHPExcel/Reader/Excel5.php';require_once 'Classes/PHPExcel/Reader/Excel2007.php';require_once 'mysql.php';header("Content-Type: text/html; charset=utf-8");$up = new FileUpload;//设置属性(上传的位置, 大小, 类型, 名是是否要随机生成)$up -> set("path", "./data/");$up -> set("maxsize", 2000000);$up -> set("allowtype", array("xlsx"));$up -> set("israndname", false);//使用对象中的upload方法, 就可以上传文件, 方法需要传一个上传表单的名子 pic, 如果成功返回true, 失败返回falseif($up -> upload("file")) {// echo '<pre>';// //获取上传后文件名子// var_dump($up->getFileName());// echo '</pre>';//$classname = $_GET['classname']; 课程名放在提交表单的时候定义$teachername = $_GET['teachername'];$teacherid = $_GET['teacherid'];if($up->getFileType() == "xlsx"){ $objReader = new PHPExcel_Reader_Excel2007();}else{ $objReader = new PHPExcel_Reader_Excel5();} $objPHPExcel = $objReader->load("./data/".$up->getFileName()); //$filename可以是上传的文件,或者是指定的文件$sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); // 取得总行数 $highestColumn = $sheet->getHighestColumn(); // 取得总列数$k = 0; //循环读取excel文件,读取一条,插入一条for($j=2;$j<=$highestRow;$j++){ $a = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();//获取A列的值$b = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//获取B列的值$c = $objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();//获取C列的值$d = $objPHPExcel->getActiveSheet()->getCell("D".$j)->getValue();//获取D列的值$sql = " INSERT INTO stusubject(subjectname,classid,teachername,teacherid,studentid,studentname,sex,class) VALUES ('','','$teachername','$teacherid','$a','$b','$c','$d');";mysql_query($sql);$k++;}if(mysql_affected_rows() >0){//echo "成功插入".mysql_affected_rows()."条数据!";//header('location:.getenv("HTTP_REFERER")');//sleep(2);// if(!isset($_COOKIE['num_students'])){// setcookie("num_students",$k);// }else{// $_COOKIE['num_students'] += $k;// }echo "<script type = 'text/javascript'>alert('数据插入成功!');var add_sub_old_url = window.localStorage.getItem('add_sub_old_url');parent.window.location.href = '../' + encodeURI(add_sub_old_url);</script>";}else{echo "<script type = 'text/javascript'>alert('数据插入失败!');var add_sub_old_url = window.localStorage.getItem('add_sub_old_url');parent.window.location.href = '../' + encodeURI(add_sub_old_url);</script>";}} else {echo '<pre>';//获取上传失败以后的错误提示var_dump($up->getErrorMsg());echo '</pre>';}
此处是文件处理的自定义类:
<?php/** file: fileupload.class.php 文件上传类FileUpload本类的实例对象用于处理上传文件,可以上传一个文件,也可同时处理多个文件上传*/class FileUpload {private $path = "./uploads"; //上传文件保存的路径private $allowtype = array('jpg','gif','png'); //设置限制上传文件的类型private $maxsize = 1000000; //限制文件上传大小(字节)private $israndname = true; //设置是否随机重命名文件, false不随机private $originName; //源文件名private $tmpFileName; //临时文件名private $fileType; //文件类型(文件后缀)private $fileSize; //文件大小private $newFileName; //新文件名private $errorNum = 0; //错误号private $errorMess=""; //错误报告消息/** * 用于设置成员属性($path, $allowtype,$maxsize, $israndname) * 可以通过连贯操作一次设置多个属性值 *@paramstring$key成员属性名(不区分大小写) *@parammixed$val为成员属性设置的值 *@returnobject返回自己对象$this,可以用于连贯操作 */function set($key, $val){$key = strtolower($key); if( array_key_exists( $key, get_class_vars(get_class($this) ) ) ){$this->setOption($key, $val);}return $this;}/** * 调用该方法上传文件 * @paramstring$fileFile上传文件的表单名称 * @returnbool 如果上传成功返回数true */function upload($fileField) {$return = true;/* 检查文件路径是滞合法 */if( !$this->checkFilePath() ) {$this->errorMess = $this->getError();return false;}/* 将文件上传的信息取出赋给变量 */$name = $_FILES[$fileField]['name'];$tmp_name = $_FILES[$fileField]['tmp_name'];$size = $_FILES[$fileField]['size'];$error = $_FILES[$fileField]['error'];/* 如果是多个文件上传则$file["name"]会是一个数组 */if(is_Array($name)){ $errors=array();/*多个文件上传则循环处理 , 这个循环只有检查上传文件的作用,并没有真正上传 */for($i = 0; $i < count($name); $i++){ /*设置文件信息 */if($this->setFiles($name[$i],$tmp_name[$i],$size[$i],$error[$i] )) {if(!$this->checkFileSize() || !$this->checkFileType()){$errors[] = $this->getError();$return=false;}}else{$errors[] = $this->getError();$return=false;}/* 如果有问题,则重新初使化属性 */if(!$return) $this->setFiles();}if($return){/* 存放所有上传后文件名的变量数组 */$fileNames = array(); /* 如果上传的多个文件都是合法的,则通过销魂循环向服务器上传文件 */for($i = 0; $i < count($name); $i++){ if($this->setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i] )) {$this->setNewFileName(); if(!$this->copyFile()){$errors[] = $this->getError();$return = false;}$fileNames[] = $this->newFileName;}}$this->newFileName = $fileNames;}$this->errorMess = $errors;return $return;/*上传单个文件处理方法*/} else {/* 设置文件信息 */if($this->setFiles($name,$tmp_name,$size,$error)) {/* 上传之前先检查一下大小和类型 */if($this->checkFileSize() && $this->checkFileType()){/* 为上传文件设置新文件名 */$this->setNewFileName(); /* 上传文件 返回0为成功, 小于0都为错误 */if($this->copyFile()){ return true;}else{$return=false;}}else{$return=false;}} else {$return=false;}//如果$return为false, 则出错,将错误信息保存在属性errorMess中if(!$return)$this->errorMess=$this->getError(); return $return;}}/** * 获取上传后的文件名称 * @paramvoid 没有参数 * @returnstring 上传后,新文件的名称, 如果是多文件上传返回数组 */public function getFileName(){return $this->newFileName;}public function getFileType(){return $this->fileType;}/** * 上传失败后,调用该方法则返回,上传出错信息 * @paramvoid 没有参数 * @returnstring 返回上传文件出错的信息报告,如果是多文件上传返回数组 */public function getErrorMsg(){return $this->errorMess;}/* 设置上传出错信息 */private function getError() {$str = "上传文件<font color='red'>{$this->originName}</font>时出错 : ";switch ($this->errorNum) {case 4: $str .= "没有文件被上传"; break;case 3: $str .= "文件只有部分被上传"; break;case 2: $str .= "上传文件的大小超过了HTML表单中MAX_FILE_SIZE选项指定的值"; break;case 1: $str .= "上传的文件超过了php.ini中upload_max_filesize选项限制的值"; break;case -1: $str .= "未允许类型"; break;case -2: $str .= "文件过大,上传的文件不能超过{$this->maxsize}个字节"; break;case -3: $str .= "上传失败"; break;case -4: $str .= "建立存放上传文件目录失败,请重新指定上传目录"; break;case -5: $str .= "必须指定上传文件的路径"; break;default: $str .= "未知错误";}return $str.'<br>';}/* 设置和$_FILES有关的内容 */private function setFiles($name="", $tmp_name="", $size=0, $error=0) {$this->setOption('errorNum', $error);if($error)return false;$this->setOption('originName', $name);$this->setOption('tmpFileName',$tmp_name);$aryStr = explode(".", $name);$this->setOption('fileType', strtolower($aryStr[count($aryStr)-1]));$this->setOption('fileSize', $size);return true;} /* 为单个成员属性设置值 */private function setOption($key, $val) {$this->$key = $val;}/* 设置上传后的文件名称 */private function setNewFileName() {if ($this->israndname) {$this->setOption('newFileName', $this->proRandName());} else{ $this->setOption('newFileName', $this->originName);} } /* 检查上传的文件是否是合法的类型 */private function checkFileType() {if (in_array(strtolower($this->fileType), $this->allowtype)) {return true;}else {$this->setOption('errorNum', -1);return false;}} /* 检查上传的文件是否是允许的大小 */private function checkFileSize() {if ($this->fileSize > $this->maxsize) {$this->setOption('errorNum', -2);return false;}else{return true;}}/* 检查是否有存放上传文件的目录 */private function checkFilePath() {if(empty($this->path)){$this->setOption('errorNum', -5);return false;}if (!file_exists($this->path) || !is_writable($this->path)) {if (!@mkdir($this->path, 0755)) {$this->setOption('errorNum', -4);return false;}}return true;}/* 设置随机文件名 */private function proRandName() {$fileName = date('YmdHis')."_".rand(100,999); return $fileName.'.'.$this->fileType; }/* 复制上传文件到指定的位置 */private function copyFile() {if(!$this->errorNum) {$path = rtrim($this->path, '/').'/';$path .= $this->newFileName;if (@move_uploaded_file($this->tmpFileName, $path)) {return true;}else{$this->setOption('errorNum', -3);return false;}} else {return false;}}}
所需要的PHPExcel框架可以自行去官网上下载。因为数据库文件都是不一样的,所以此处就不提供了,就是普通的mysql数据库,模板文件中给定好与数据库中相应的字段,这样就不会有意外错误了。
阅读全文
0 0
- PHP文件上传数据存入数据库
- 上传xls文件并解析数据存入msyql数据库
- .net上传文件时同时将数据存入数据库
- php实现文件上传到指定文件夹,文件路径或名字存入数据库,如何实现啊
- php实现文件上传到指定文件夹,文件路径或名字存入数据库,如何实现啊
- 上传Excel文件并读取存入数据库
- 以数据流的形式上传上传数据存入数据库
- 读取文本.EFZ文件数据,存入数据库
- 将上传文件以二进制形式存入数据库中,并下载数据库中的二进制数据生成对应的文件
- servlet文件上传后改名存入数据库中。。。。
- 上传excel文件并在服务器端读取存入数据库
- C# 上传文件并将路径存入数据库
- springboot上传文件(存入服务器,并将URL存入数据库表中)
- PHP上传Excel文件导入数据到MySQL数据库示例
- php将json格式的数据直接存入mysql数据库
- php将json格式的数据直接存入mysql数据库
- PHP生成百万个UID存入文件、插入数据库
- 把文件存入数据库
- 第一章 Java基础
- synchronized学习笔记1
- Android 发送和接收定制广播
- HDU
- 从高考到程序员的成长之路
- PHP文件上传数据存入数据库
- ListView的优化
- [Swift]iOS动画:下载动画
- sql
- Apache 服务配置二级域名
- 一步解决Mac OS下MySQL数据库无法输入汉字的问题
- 弹出框和提示框效果以及代码展示
- 在六月天
- leetcode 300. Longest Increasing Subsequence