如何在MySQL中直接儲存圖片

來源:互聯網
上載者:User

如果你想把二進位的資料,比如說圖片檔案和HTML檔案,直接儲存在你的MySQL資料庫,那麼這篇文章就是為你而寫的!我將告訴你怎樣通過HTML表單來儲存這些檔案,怎樣訪問和使用這些檔案。

本文概述: 

在mysql中建立一個新的資料庫 

一個怎樣儲存檔案的例子程式 

一個怎樣訪問檔案的例子程式 

在mysql中建立一個新的database

首先,你必須在你的mysql中建立一個新的資料庫,我們將會把那些二進位檔案儲存在這個資料庫裡。在例子中我會使用下列結構,為了建立資料庫,你必須做下列步驟: 

進入MySql控制器 

輸入命令"create database binary_data;" 

輸入命令"use binary_data;"

輸入命令"CREATE TABLE binary_data ( id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY,
description CHAR(50), bin_data LONGBLOB, filename CHAR(50), filesize CHAR(50), filetype CHAR(50));" (不能斷行) 

如果沒有意外,資料庫和表應該建立好了。 

一個怎樣儲存檔案的例子程式用這個例子你可以通過Html表單將檔案傳輸到資料庫中。.

store.php3

以下為引用的內容:
<?php
// store.php3 - by Florian Dittmer <dittmer@gmx.net>
?>
<HTML>
<HEAD><TITLE>Store binary data into SQL Database</TITLE></HEAD>
<BODY>
<?php
// 如果提交了表單,代碼將被執行:
if ($submit) {
// 串連到資料庫
// (你可能需要調整主機名稱,使用者名稱和密碼)
MYSQL_CONNECT( "localhost", "root", "password");
mysql_select_db( "binary_data");
$data = addslashes(fread(fopen($form_data, "r"), filesize($form_data)));
$result=MYSQL_QUERY( "INSERT INTO binary_data (description,bin_data,filename,filesize,filetype) ".
"VALUES (’$form_description’,’$data’,’$form_data_name’,’$form_data_size’,’$form_data_type’)");
$id= mysql_insert_id();
print "<p>This file has the following Database ID: <b>$id</b>";
MYSQL_CLOSE();
} else {
// 否則顯示儲存新資料的表單
?>
<form method="post" action=" <?php echo $PHP_SELF; ?>" enctype="multipart/form-data">
File Description:<br>
<input type="text" name="form_description" size="40">
<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="1000000">
<br>File to upload/store in database:<br>
<input type="file" name="form_data" size="40">
<p><input type="submit" name="submit" value="submit">
</form>
<?php
}
?>
</BODY>
</HTML>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.