標籤:
近期的項目由於特殊原因,需要將檔案存到資料庫中。今天特地測試,首先在php網站上傳檔案,將檔案讀取出來——再存入到MySQL資料庫中。
一、首先建立php 代碼如下(網上找了段代碼進行過修改):原始碼 http://blog.csdn.net/jonathanlin2008/article/details/6185162
<?php/** * Created by PhpStorm. * User: yun * Date: 2015/7/10 * Time: 22:04 *///echo md5(‘ggHScquI8EzIPSwV‘);if($_SERVER[‘REQUEST_METHOD‘] == ‘POST‘){ $myfile=$_FILES[‘myfile‘]; /* echo file_get_contents($myfile[‘tmp_name‘]); exit;*/if($myfile != "none" && $myfile != "") { //有了上傳檔案了 //設定逾時限制時間,預設時間為 30秒,設定為0時為不限時 $time_limit=60; set_time_limit($time_limit); // //名字,大小,檔案格式, $file_name=$myfile[‘name‘]; $file_size=$myfile[‘size‘]; $file_type=strstr ( $file_name, ‘.‘ ); //把檔案內容讀到字串中 直接在讀取的臨時檔案,因為不需要將檔案放到目錄中。 $fp=fopen($myfile[‘tmp_name‘], "rb"); if(!$fp) die("file open error"); $file_data = addslashes(fread($fp, $file_size)); fclose($fp); /* $dbh = new PDO ( ‘mysql:host=192.168.1.168;port=3306;dbname=testdb;‘, ‘root‘, ‘123‘ );*/ /*下面是將pdo進行了一個簡單的封裝*/ $userclass = dirname(__FILE__) . ‘/source/module/User.php‘; require_once($userclass); $user = new User(); /*t_testfile 表中file欄位資料類型為longblod*/ $sql="insert into t_testfile (file) values (‘$file_data‘)"; $result=$user->db->doSql($sql); //下面這句取出了剛才的insert語句的id $id=$user->db->getLastId(); echo "上傳成功--- "; echo "<a href=‘show_info.php?id=$id‘>顯示上傳檔案資訊</a>";}else { echo "你沒有上傳任何檔案";}}/* function doSql($sql, $model = ‘many‘, $debug = false){ if ($debug) echo $sql; $this->sth = $this->dbh->query($sql); $this->getPDOError(); $this->sth->setFetchMode(PDO::FETCH_ASSOC); if ($model == ‘many‘) { $result = $this->sth->fetchAll(); } else { $result = $this->sth->fetch(); } $this->sth = null; return $result;}*/?><!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title>測試檔案上傳並存入到MySQL資料庫中</title> <script src="../js/jquery-1.8.3.min.js"></script></head><body> <div> <form enctype=‘multipart/form-data‘ name=‘myform‘ action=‘uploadtest.php‘ method=‘post‘> <input type="file" id="myfile" name="myfile" /> <input type="submit" id="btnupload" value="上傳檔案"/> </form> </div></body></html>
二、遇到問題:檔案大於php預設大小是,上傳擷取不到檔案,直接報“你沒有上傳任何檔案”
所以:調整php.ini設定檔中的參數,後重啟Apache服務。
調整的變數:
file_uploads = On ;開啟檔案上傳選項
upload_max_filesize = 500M ;上傳檔案上限
如果要上傳比較大的檔案,僅僅以上兩條還不夠,必須把伺服器緩衝上限調大,把指令碼最大執行時間變長
post_max_size = 500M ;post上限
max_execution_time = 1800 ; Maximum execution time of each script, in seconds指令碼最大執行時間
max_input_time = 1800 ; Maximum amount of time each script may spend parsing request data
memory_limit = 128M ; Maximum amount of memory a script may consume (128MB)記憶體上限
三、點擊上傳又出現一個問題。MySQL server has gone away,由於英語很菜,直接有道翻譯:‘MySQL伺服器已經消失’
百度(還是要感謝百度,和廣大牛人的分享)讓我找到瞭解決方法,不至於迷失很久。
解決方案:http://www.cnblogs.com/cenalulu/archive/2013/01/08/2850820.html
php+mysql存取檔案