1将文件存到项目路径下,保存图片的路径
2.二进制的数据生成对应的图片,如果你想把二进制的数据,比如说图片文件和HTML文件,直接保存在你的MySQL数据库,那么这篇文章就是为你而写的!我将告诉你怎样通过HTML表单来储存这些文件,怎样访问和使用这些文件。
PHP 自动将图片转换成BASE64
- <?php
- function base64_encode_image ($filename='string',$filetype='string') {
- if ($filename) {
- $imgbinary = fread(fopen($filename, "r"), filesize($filename));
- //file_put_contents('b.png',$imgbinary);
- return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
- }
- }
- ?>
- <img src="<?php echo base64_encode_image ('a.png','png'); ?>"/>
二、在MySQL中建立一个新的database
首先,你必须在你的MySQL中建立一个新的数据库,我们将会把那些二进制文件储存在这个数据库里。在例子中我会使用下列结构,为了建立数据库,你必须做下列步骤:
- CREATE TABLE `binary_data` (
- `id` int(4) NOT NULL AUTO_INCREMENT,
- `description` char(50) DEFAULT NULL,
- `bin_data` longblob,
- `filename` char(50) DEFAULT NULL,
- `filesize` char(50) DEFAULT NULL,
- `filetype` char(50) DEFAULT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf-8;
输入如下命令:
- <?php
- if ($_FILES ['myfile'] != "none" && $_FILES ['myfile'] != "") {
- $time_limit = 60;
- set_time_limit ( $time_limit );
- $file_type = $_FILES ['myfile'] ['type'];
- $file_name = $_FILES ['myfile'] ['name'];
- $file_size = $_FILES ['myfile'] ['size'];
- $fp = fopen ( $_FILES ['myfile'] ['tmp_name'], "rb" );
- if (! $fp)
- die ( "file open error" );
- $file_data = addslashes ( fread ( $fp, $file_size ) );
- fclose ( $fp );
- /** 等价
- $file_data = file_get_contents($_FILES["myfile"]['tmp_name']);
- */
- $conn = mysql_connect ( "localhost", "root", "root" );
- if (! $conn)
- die ( "error : mysql connect failed" );
- mysql_select_db ( "test", $conn );
- $sql = "insert into receive(file_data,file_type,file_name,file_size)values ('$file_data','$file_type','$file_name',$file_size)";
- $result = mysql_query ( $sql );
- $id = mysql_insert_id ();
- mysql_close ( $conn );
- set_time_limit ( 30 ); //恢复缺省超时设置
- echo "上传成功--- ";
- echo "<a href='show_info.php?id=$id'>显示上传文件信息</a>";
- } else {
- echo "你没有上传任何文件";
- }
- ?>
(5)show_add.php //从数据库里取出文件内容 http://hudeyong926.iteye.com/blog/898072
- <?php
- $data = mysql_result($result, 0, "file_data");
- $type = mysql_result($result, 0, "file_type");
- $fileName = mysql_result($result, 0, "file_name");
- mysql_close($conn);
- $filePath = 'download/' . $userid . "/" . $fileName;
- file_put_contents($fileName,$data);
- header('Location: /download.php?fileName=' . $fileName . '&file=' . $filePath);
- /*
- //download.php
- $fileName = $_GET['fileName'];
- $file_dir = RelativePath . $_GET['file'];
- $file = @ fopen($file_dir, "r");
- if (!$file) {
- echo "File does not exist.";
- } else {
- ob_end_clean();
- Header("Content-type: application/octet-stream");
- Header("Content-Disposition: attachment; filename=" . $fileName);
- while (!feof($file)) {
- echo fread($file, 50000);
- }
- fclose($file);
- }
- */
- ?>
时间: 2024-11-03 17:13:22