php实现上传图片保存到数据库的方法
- 格式:doc
- 大小:20.00 KB
- 文档页数:3
用纯ASP代码实现图片上传到指定文件夹并存入数据库中的代码用ASP编写网站应用程序时间长了,难免会遇到各式各样的问题,其中关于如何上传文件到服务器恐怕是遇见最多的问题了,尤其是上传图片,比如你想要在自己的社区里面实现类似网易虚拟社区提供的“每日一星”的功能,就要提供给网友上传照片的功能。
上传图片文件到服务器可以使用各种免费的文件上传组件,使用起来功能虽然很强大,但是由于很多情况下,我们只能使用免费的支持ASP的空间或者租用别人的虚拟空间,对于第一种情况,我们根本就没有可能来使用文件上传组件;至于第二种情况,我们也要付出不少的“银子”才可以。
除非你拥有自己的虚拟主机,你就可以随便的在服务器上面安装自己所需要的组件,这种情况对于大多数人来说是可望而不可及的。
那我们就没有办法了吗?呵呵,答案是肯定的(当然是肯定的了,要不然我也没法写出这篇文章啊)。
下面就让我们一起来使用纯ASP代码来实现图片的上传以及保存到数据库的功能(顺便也实现显示数据库中的图片到网页上的功能)。
首先我们先来熟悉一下将要使用的对象方法。
我们用来获取上一个页面传递过来的数据一般是使用Request对象。
同样的,我们也可以使用Request对象来获取上传上来的文件数据,使用的方法是Request.BinaryRead()。
而我们要从数据库中读出来图片的数据显示到网页上面要用到的方法是:Request.BinaryWrite()。
在我们得到了图片的数据,要保存到数据库中的时候,不可以直接使用Insert语句对数据库进行操作,而是要使用ADO的AppendChunk方法,同样的,读出数据库中的图片数据,要使用GetChunk 方法。
各个方法的具体语法如下:* Request.BinaryRead语法:variant = Request.BinaryRead(count)参数variant返回值保存着从客户端读取到数据。
count指明要从客户端读取的数据量大小,这个值小于或者等于使用方法Request.TotalBytes得到的数据量。
PHP上传图⽚到数据库并显⽰的实例代码PHP上传图⽚到数据库并显⽰1、创建数据表CREATE TABLE ccs_image (id int(4) unsigned NOT NULL auto_increment,description varchar(250) default NULL,bin_data longblob,filename varchar(50) default NULL,filesize varchar(50) default NULL,filetype varchar(50) default NULL,PRIMARY KEY (id))engine=myisam DEFAULT charset=utf82、⽤于上传图⽚到服务器的页⾯ upimage.html<!doctype html><html><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><style type="text/css">*{margin: 1%}</style><title>Document</title></head><body><form method="post" action="upimage.php" enctype="multipart/form-data">描述:<input type="text" name="form_description" size="40"><input type="hidden" name="MAX_FILE_SIZE" value="1000000"> <br>上传⽂件到数据库:<input type="file" name="form_data" size="40"><br><input type="submit" name="submit" value="submit"></form></body></html>3、处理图⽚上传的php upimage.php<?phpif (isset($_POST['submit'])) {$form_description = $_POST['form_description'];$form_data_name = $_FILES['form_data']['name'];$form_data_size = $_FILES['form_data']['size'];$form_data_type = $_FILES['form_data']['type'];$form_data = $_FILES['form_data']['tmp_name'];$dsn = 'mysql:dbname=test;host=localhost';$pdo = new PDO($dsn, 'root', 'root');$data = addslashes(fread(fopen($form_data, "r"), filesize($form_data)));//echo "mysqlPicture=".$data;$result = $pdo->query("INSERT INTO ccs_image (description,bin_data,filename,filesize,filetype) VALUES ('$form_description','$data','$form_data_name','$form_data_size','$form_data_type')"); if ($result) {echo "图⽚已存储到数据库";} else {echo "请求失败,请重试";注:图⽚是以⼆进制blob形式存进数据库的,像这样4、显⽰图⽚的php getimage.php<?php$id =2;// $_GET['id']; 为简洁,直接将id写上了,正常应该是通过⽤户填⼊的id获取的$dsn ='mysql:dbname=test;host=localhost';$pdo = new PDO($dsn,'root','root');$query = "select bin_data,filetype from ccs_image where id=2";$result = $pdo->query($query);$result = $result->fetchAll(2);// var_dump($result);$data = $result[0]['bin_data'];$type = $result[0]['filetype'];Header( "Content-type: $type");echo $data;5、到浏览器查看已经上传的图⽚,看是否可以显⽰以上就是本次介绍的全部相关知识点,感谢⼤家的学习和对的⽀持。
php上传图⽚的代码并保存到数据库connet.php数据库⽂件<?phpmysql_connect("localhost","root",123)or die("sorry");mysql_select_db("db_user");mysql_query("set names utf8");>do_photo.php⽂件<?php//上传你的头像session_start();if(isset($_POST['update'])){include("connect.php");//限制上传照⽚的类型function photo_type($photo_file){//查找"."第⼀次出现的位置//strrpos() 函数查找字符串在另⼀个字符串中最后⼀次出现的位置。
如果成功,则返回位置,否则返回 false。
$position=strrpos($photo_file,".");//如果返回不是false//substr() ⽅法可在字符串中抽取从 start 下标开始的指定数⽬的字符。
//global $suffix;$suffix=substr($photo_file,$position+1,strlen($photo_file)-$position);return $suffix;//定义图⽚上传的⽬录名称//diretory(upload file)}//$photo_name=$_FILES['myform']['name'];$ext=photo_type($_FILES['myform']['name']);//strtolower()转换⼩写 strtoupper()转换⼤写//$ext=strtolower($ext);$upload_dir='./upload/';if($suffix!="jpg" && $suffix!="gif"){die("不⽀持这个类型的图⽚");}//转移到./upload///mova_uploaded_file()$uploadfile=$upload_dir.time().".".$suffix;if(move_uploaded_file($_FILES['myform']['tmp_name'],$uploadfile)){$sql1="update yonjian set photo='{$uploadfile}' where id='{$_SESSION['id']}'";if(mysql_query($sql1)){header("location:account.php");}}}><form name="ljklj" action="do_photo.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="2000000">⽂件<input name="myform" type="file" value="浏览" ><input type="submit" name="update" value="update"></form>请诸位⾼⼿多给建议,我在此多谢数据库为/*Navicat MySQL Data TransferSource Server : jiangSource Server Version : 50155Source Host : localhost:3306Source Database : db_userTarget Server Type : MYSQLTarget Server Version : 50155File Encoding : 65001Date: 2011-11-09 22:12:56*/SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for `photo`-- ----------------------------DROP TABLE IF EXISTS `photo`;CREATE TABLE `photo` (`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(50) DEFAULT NULL,`photo` varchar(300) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=gbk;-- ------------------------------ Records of photo-- ----------------------------。
两种php实现图⽚上传的⽅法图⽚上传在项⽬中经常⽤到,⼏乎没有任何⼀个项⽬可以脱离图⽚或者是⽂件上传。
本篇我在这向⼤家介绍两种常规的上传⽅式。
(注:在这⾥我们仅仅是对功能的实现,不去做过多的前端的样式)⼀、利⽤form表单上传此种⽅式是最原始的上传⽅式,前端就是简单的form表单,后端我们有PHP处理传输过来的⽂件。
⾸先看前端的代码 upload.html<form action="handle.php" name="form" method="post" enctype="multipart/form-data"><input type="file" name="file" /><input type="submit" name="submit" value="上传" /></form>然后新建php⽂件 handle.php 代码如下$file = $_FILES['file'];//得到传输的数据//得到⽂件名称$name = $file['name'];$type = strtolower(substr($name,strrpos($name,'.')+1)); //得到⽂件类型,并且都转化成⼩写$allow_type = array('jpg','jpeg','gif','png'); //定义允许上传的类型//判断⽂件类型是否被允许上传if(!in_array($type, $allow_type)){//如果不被允许,则直接停⽌程序运⾏return ;}//判断是否是通过HTTP POST上传的if(!is_uploaded_file($file['tmp_name'])){//如果不是通过HTTP POST上传的return ;}$upload_path = "D:/now/"; //上传⽂件的存放路径//开始移动⽂件到相应的⽂件夹if(move_uploaded_file($file['tmp_name'],$upload_path.$file['name'])){echo "Successfully!";}else{echo "Failed!";}当然,此php处理代码不是很完善,其中对错误的情况没有进⾏处理,然⽽使⽤php处理上传⽂件的原理就是这样的,⼤家可以在此基础上进⾏优化,使其更加完善。
用php实现的获取网页中的图片并保存到本地的代码用php实现的获取网页中的图片并保存到本地的代码-PHPphp技巧<?phpheader("Content-type:image/jpeg");function read_url($str){$file=fopen($str,"r");while(!feof($file)){$result.=fgets($file,9999);}fclose($file);return $result;}function save_img($str){$result=read_url($str);$result=str_replace("\"","",$result);$result=str_replace("\'","",$result);preg_match_all('/|>)/i',$result,$matches);foreach($matches[1] as $value){echo $value."\n";//GrabImage($value,$filename="");}}// $url 是远程图片的完整URL地址,不能为空。
// $filename 是可选变量: 如果为空,本地文件名将基于时间和日期// 自动生成.function GrabImage($url,$filename="") {if($url==""):return false;endif;$path="download/"; //指定存储文件夹//若文件不存在,则创建;if(!file_exists($path)){mkdir($path);}if($filename=="") {$ext=strrchr($url,".");if($ext!=".gif" && $ext!=".jpg"):return false;endif;$filename=$path.date("dMYHis").$ext;}ob_start();readfile($url);$img = ob_get_contents();ob_end_clean();$size = strlen($img);$fp2=@fopen($filename, "a");fwrite($fp2,$img);fclose($fp2);return $filename;}save_img("/doc/e68326675.html,"); ?>。
图⽚如何存⼊数据库通常对⽤户上传的图⽚需要保存到数据库中。
解决⽅法⼀般有两种:⼀种是将图⽚保存的路径存储到数据库;另⼀种是将图⽚以⼆进制数据流的形式直接写⼊数据库字段中。
以下为具体⽅法: ⼀、保存图⽚的上传路径到数据库: string uppath="";//⽤于保存图⽚上传路径 //获取上传图⽚的⽂件名 string fileFullname = this.FileUpload1.FileName; //获取图⽚上传的时间,以时间作为图⽚的名字可以防⽌图⽚重名 string dataName = DateTime.Now.ToString("yyyyMMddhhmmss"); //获取图⽚的⽂件名(不含扩展名) string fileName = fileFullname.Substring(stIndexOf("\\") + 1); //获取 string type = fileFullname.Substring(stIndexOf(".") + 1); //判断是否为要求的格式 if (type == "bmp" || type == "jpg" || type == "jpeg" || type == "gif" || type == "JPG" || type == "JPEG" || type == "BMP" || type == "GIF") { //将图⽚上传到指定路径的⽂件夹 this.FileUpload1.SaveAs(Server.MapPath("~/upload") + "\\" + dataName + "." + type); //将路径保存到变量,将该变量的值保存到数据库相应字段即可 uppath = "~/upload/" + dataName + "." + type; } ⼆、将图⽚以⼆进制数据流直接保存到数据库: 引⽤如下: using System.Drawing; using System.IO; using System.Data.SqlClient; 设计数据库时,表中相应的字段类型为iamge 保存: //图⽚路径 string strPath = this.FileUpload1.PostedFile.FileName.ToString (); //读取图⽚ FileStream fs = new System.IO.FileStream(strPath, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); byte[] photo = br.ReadBytes((int)fs.Length); br.Close(); fs.Close(); //存⼊ SqlConnection myConn = new SqlConnection("Data Source=.;Initial Catalog=stumanage;User ID=sa;Password=123"); string strComm = " INSERT INTO stuInfo(stuid,stuimage) VALUES(107,@photoBinary )";//操作数据库语句根据需要修改 SqlCommand myComm = new SqlCommand(strComm, myConn); myComm.Parameters.Add("@photoBinary", SqlDbType.Binary, photo.Length); myComm.Parameters["@photoBinary"].Value = photo; myConn.Open(); if (myComm.ExecuteNonQuery() > 0) { bel1.Text = "ok"; } myConn.Close(); 读取: ...连接数据库字符串省略 mycon.Open(); SqlCommand command = new SqlCommand("select stuimage from stuInfo where stuid=107", mycon);//查询语句根据需要修改 byte[] image = (byte[])command.ExecuteScalar (); //指定从数据库读取出来的图⽚的保存路径及名字 string strPath = "~/Upload/zhangsan.JPG"; string strPhotoPath = Server.MapPath(strPath); //按上⾯的路径与名字保存图⽚⽂件 BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate)); bw.Write(image); bw.Close(); //显⽰图⽚ this.Image1.ImageUrl = strPath; 采⽤俩种⽅式可以根据实际需求灵活选择。
php将图⽚以⼆进制存到mysql中的⽅法很奇怪,直接⽤file_get_contents存⼊数据库成功后,结果读取的时候图⽚不能显⽰,后来解决⽅法是什么!!是⽤了下base64编码。
不多说直接上图。
1.这是upload.php<?phpinclude('./conn.php');if ($_POST['submit']) {if ($_FILES['image']['size']) {$names = $_FILES['image']['name'];$arr = explode('.', $names);$name = $arr[0]; //图⽚名称$date = date('Y-m-d H:i:s'); //上传⽇期$fp = fopen($_FILES['image']['tmp_name'], 'rb');$type = $_FILES['image']['type'];$file_uploads = file_get_contents($_FILES['image']['tmp_name']);$file_uploads = base64_encode($file_uploads);if (!$fp) {showInfo('读取图⽚失败!');} else {if ($image) {$q = "insert into image (name, pic, type, date) values ('$name','$file_uploads','$type','$date')";$result = mysql_query($q);if ($result) {showInfo('上传成功!');} else {showInfo('上传失败!');}mysql_close($link);} else {showInfo('请选择要上传的⽂件!');}}} else {showInfo('请选择要上传的⽂件!');}}function showInfo($info){echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";echo "<meta http-equiv='refresh' content='1;url=show.php'>";echo "</head>";echo "<body>" . $info . "……</body>";echo "</html>";}>2.image.php⽤于从数据库中读取图⽚<?phpinclude('./conn.php');$id = $_GET['id'];$sql = "select * from image where id='$id'";$result = mysql_query($sql);if (!$result)die("读取图⽚失败!");$num = mysql_num_rows($result);if ($num < 1)die("暂⽆图⽚");$obj = mysql_fetch_object($result);$data = base64_decode($obj->pic); //Base64解码$type = mysql_result($result, 0, 'type');header("Content-type: $type");echo$data;>3.show.php显⽰和上传图⽚<?phpinclude('./conn.php');><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml" lang="en_US" xml:lang="en_US"><head><meta http-equive="Content-Type" content=text/html charset=utf-8><title> </title></head><body><form method='post' action='./upload.php' enctype="multipart/form-data"><input type="file" name="image" /><input type="submit" name="submit" value="上传" /></form><!-----------显⽰图⽚---------------------><table><?php$ret = mysql_query('select * from image order by id desc');if ($ret) {while ($row = mysql_fetch_array($ret)) {><tr><td style='width:170px;'><img src="image.php?id=<?phpecho $row[id];>" width="170" height="150" border="0"><div style='text-align:center;'><?phpecho$row['name'];></div><?phpecho$row['date'];></td></tr><?php}}></table><!-----------/显⽰图⽚---------------------></body></html>最后运⾏结果:总结:⽹上的都是坑爹么?谁有其他不⽤base64编码的⽅法能否告知?。
PHP使⽤curl请求实现post⽅式上传图⽚⽂件功能⽰例本⽂实例讲述了PHP使⽤curl请求实现post⽅式上传图⽚⽂件功能。
分享给⼤家供⼤家参考,具体如下:在调⽤第三⽅api接⼝时,有时会遇到通过http协议上传图⽚,以下是⼀个微信公众平台新增永久素材的例⼦;php代码:/* 使⽤curl函数 */$url = "https:///cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=image";$post_data = array('media' => '@bag03.jpg',);$response = curl_http($url, 'POST', $post_data);$params = array();$params = json_decode($response,true);if (isset($params['errcode'])){echo "error:" . $params['errcode'];echo "msg :" . $params['errmsg'];exit;}var_dump( $params );/*** http请求⽅式: 默认GET*/function curl_http($url, $method="GET", $postfields){$ch = curl_init();curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);curl_setopt($ch, CURLOPT_URL, $url);switch ($method) {case "POST":curl_setopt($ch, CURLOPT_POST, true);if (!empty($postfields)) {$hadFile = false;if (is_array($postfields) && isset($postfields['media'])) {/* ⽀持⽂件上传 */if (class_exists('\CURLFile')) {curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);foreach ($postfields as $key => $value) {if (isPostHasFile($value)) {$postfields[$key] = new \CURLFile(realpath(ltrim($value, '@')));$hadFile = true;}}} elseif (defined('CURLOPT_SAFE_UPLOAD')) {if (isPostHasFile($value)) {curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);$hadFile = true;}}}$tmpdatastr = (!$hadFile && is_array($postfields)) ? http_build_query($postfields) : $postfields;curl_setopt($ch, CURLOPT_POSTFIELDS, $tmpdatastr);}break;default:curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求⽅式 */break;}$ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;curl_setopt($ch, CURLOPT_URL, $url);if($ssl){curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求不验证证书和hostscurl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在}$response = curl_exec($ch);curl_close($ch);if(empty($response)){exit("错误请求");}return $response;}function isPostHasFile($value){if (is_string($value) && strpos($value, '@') === 0 && is_file(realpath(ltrim($value, '@')))) {return true;}return false;}也可以使⽤php内置的系统函数,如果使⽤过程中出现问题,建议查看是否启⽤相应的系统函数。
在我们设计和制作网站的过程中,有时把图片保存到数据库中要比存成文件的形式更加方便。
PHP和MySQL这对黄金组合可以很容易的实现上述功能。
在本文中,我们将会向读者介绍如何把图片保存到MySQL数据库中以及如何将数据库中的图片显示出来。
设置数据库我们通常在数据库中所使用的文本或整数类型的字段和需要用来保存图片的字段的不同之处就在于两者所需要保存的数据量不同。
MySQL数据库使用专门的字段来保存大容量的数据,数据类型为BLOB。
MySQL数据库为BLOB做出的定义如下:BLOB数据类型是一种大型的二进制对象,可以保存可变数量的数据。
BLOB具有四种类型,分别是TINYBLOB,BLOB, MEDIUMBLOB 和LONGBLOB,区别在于各自所能够保存的最大数据长度不同。
在介绍了所需要使用的数据类型之后,我们可以使用以下语句创建保存图象的数据表。
CREATE TABLE Images ( PicNum int NOT NULL AUTO_INCREMENT PRIMARY KEY, Image BLOB );编写上传脚本关于如何实现文件的上传,我们在这里就不再介绍了。
现在,我们主要来看一下如何接收上传文件并将其存入到MySQL数据库中。
具体的脚本代码如下,其中我们假定文件上传域的名称为Picture。
<? If($Picture != "none") { $PSize = filesize($Picture); $mysqlPicture = addslashes(fread (fopen($Picture, "r"), $PSize)); mysql_connect($host,$username,$password) or die("Unable to connect to SQL server"); @mysql_select_db($db) or die("Unable to select database"); mysql_query("INSERT INTO Images (Image) VALUES '($mysqlPicture')") or die("Can't Perform Query"); } else { echo"You did not upload any picture"; } ?>这样,我们就可以成功的把图片保存到数据库中。
php上传图⽚之时间戳命名(保存路径)html代码:<div id="images" style="width:250px;height:120px;background:#fff;border:1px solid #ccc;"><h2><strong>图⽚导⼊</strong></h2><form enctype="multipart/form-data" action="./includer/importimg.inc.php?action=img" method="post" name="imge"><input type="hidden" name="MAX_FILE_SIZE" value="100000000" /><input value="导⼊⽂件" type="file" name="img" id="file"/><br/><br/><input type="submit" id="imgbut" class="buttons" value="上传图⽚" /></form></div>php代码:<?php/***Mwbe Version1.0*-----------------------------------------------*Copy 2013-2014 ylt*Web: communicate*-----------------------------------------------*Author: tao *Data: 2014-7-22*/header("Content-Type:text/html;charset=utf-8");//step 1 使⽤$_FILES['pic']["error"] 检查错误if(isset($_GET["action"])=="img"){if($_FILES["img"]["error"] > 0){switch($_FILES["img"]["error"]) {case 1:echo "<script type='text/javascript'>alert('上传的⽂件超过了 php.ini 中 upload_max_filesize 选项限制的值<br>');history.back();</script>"; break;case 2:echo "<script type='text/javascript'>alert('上传⽂件的⼤⼩超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值');history.back();</script>"; break;case 3:echo "<script type='text/javascript'>alert('⽂件只有部分被上传');history.back();</script>";break;case 4:echo "<script type='text/javascript'>alert('没有⽂件被上传');history.back();</script>";break;default:echo "<script type='text/javascript'>alert('末知错误');history.back();</script>";}exit;}$maxsize=2000000; //50k//step 2 使⽤$_FILES["pic"]["size"] 限制⼤⼩单位字节 2M=2000000if($_FILES["img"]["size"] > $maxsize ) {echo "<script type='text/javascript'>alert('上传的⽂件太⼤,不能超过{$maxsize}字节');history.back();</script>";exit;}//step 3 使⽤$_FILES["pic"]["type"]或是⽂件的扩展名限制类型 MIME image/gif image/png gif png jpg/* list($dl, $xl) = explode("/", $_FILES["pic"]["type"]);if($dl!="image"){echo "请上传⼀个图⽚,不充许其它类型⽂件";exit;}*/$allowtype=array("png", "gif", "jpg", "jpeg");$arr=explode(".", $_FILES["img"]["name"]);$hz=$arr[count($arr)-1];if(!in_array($hz, $allowtype)){echo "<script type='text/javascript'>alert('这是不允许的类型');history.back();</script>";exit;}//step 4 将让传后的⽂件名改名$filepath="../imgweb/";$fileimgweb="imgweb/";//为了符合UBB的路径$randname=date("Y").date("m").date("d").date("H").date("i").date("s").rand(100, 999).".".$hz;//将临时位置的⽂件移动到指定的⽬录上即可if(is_uploaded_file($_FILES["img"]["tmp_name"])){if(move_uploaded_file($_FILES["img"]["tmp_name"],$filepath.$randname)){echo "<script type='text/javascript'>history.back();</script>";session_start();$_SESSION['images'] = $fileimgweb.$randname;}else{echo "<script type='text/javascript'>alert('上传失败');history.back();</script>";}}else{echo"<script type='text/javascript'>alert('不是⼀个上传⽂件');history.back();</script>"; }}>。
实用标准文案1.上传图片到指定的文件夹,并且把图片的路径存到数据库里面。
//判断上传是否有文件if (FileUpload1.HasFile){string filepath = FileUpload1.PostedFile.FileName.ToString();//将图片保存到项目文件夹image里面string fileName = System.IO.Path.GetFileName(filepath);string savePaht = Server.MapPath("images/" + fileName); FileUpload1.SaveAs(savePaht);string strSql = "insert into userInfo (userimage) values ('"+ filepath+"')";// string strSql = "insert into userInfo (userimage) values (@image)";//userInfo 是表名 userimage是图片的字段Sqlconnection conn=new Sqlconnection(@"数据库的连接字符串");SqlCommand cmd = new SqlCommand(strSql, conn);conn.open();//cmd.parameters.add("@image",sqldbtype.varchar,100).value="./image"+filepath;cmd.ExecuteNonQuery();}2.遍历文件夹里面的图片,显示在datalist里面//获取图片所在的文件夹的路径DirectoryInfo imagesfile = new DirectoryInfo(Server.MapPath("./images"));//绑定数据源DataList1.DataSource = imagesfile.GetFiles("*.jpg");DataList1.DataBind();<asp:DataList ID="DataList1" runat="server" RepeatColumns="3"><ItemTemplate><asp:image ID="Image1" runat="server" width="120"ImageUrl='<%#"image/" +Eval("Name")%>'/></ItemTemplate></asp:DataList>精彩文档。
PHP实现上传⽂件并存进数据库的⽅法本⽂实例讲述了PHP实现上传⽂件并存进数据库的⽅法。
分享给⼤家供⼤家参考。
具体如下:show_add.php⽂件如下:<?phpif(!isset($_REQUEST['id']) or $_REQUEST['id']=="") die("error: id none");$id = $_REQUEST['id'];//定位记录,读出$conn=mysql_connect("localhost","root","admin");if(!$conn) die("error: mysql connect failed");mysql_select_db("nokiapaymentplat",$conn);$sql = "select * from receive where id=$id";$result = mysql_query($sql,$conn);if(!$result) die("error: mysql query");$num=mysql_num_rows($result);if($num<1) die("error: no this recorder");$data = mysql_result($result,0,"file_data");$type = mysql_result($result,0,"file_type");$name = mysql_result($result,0,"file_name");mysql_close($conn);//先输出相应的⽂件头,并且恢复原来的⽂件名header("Content-type:$type");header("Content-Disposition: attachment; filename=$name");echo $data;>show_info.php⽂件如下:<?phpif(!isset($_REQUEST['id']) or $_REQUEST['id']=="") die("error: id none");$id = $_REQUEST['id'];//定位记录,读出$conn=mysql_connect("localhost","root","admin");if(!$conn) die("error: mysql connect failed");mysql_select_db("nokiapaymentplat",$conn);$sql = "select file_name ,file_size from receive where id=$id";$result = mysql_query($sql,$conn);if(!$result) die(" error: mysql query");//如果没有指定的记录,则报错$num=mysql_num_rows($result);if($num<1) die("error: no this recorder");//下⾯两句程序也可以这么写//$row=mysql_fetch_object($result);//$name=$row->name;//$size=$row->size;$name = mysql_result($result,0,"file_name");$size = mysql_result($result,0,"file_size");mysql_close($conn);echo "<hr>上传的⽂件的信息:";echo "<br>The file's name - $name";echo "<br>The file's size - $size";echo "<br><a href=show_add.php?id=$id>附件</a>";>submit.php⽂件如下:<?phpif(is_uploaded_file($_FILES['myfile']['tmp_name'])) {//有了上传⽂件了$myfile=$_FILES["myfile"];//设置超时限制时间,缺省时间为 30秒,设置为0时为不限时$time_limit=60;set_time_limit($time_limit); ////把⽂件内容读到字符串中$fp=fopen($myfile['tmp_name'], "rb");if(!$fp) die("file open error");$file_data = addslashes(fread($fp, filesize($myfile['tmp_name'])));fclose($fp);unlink($myfile['tmp_name']);//⽂件格式,名字,⼤⼩$file_type=$myfile["type"];$file_name=$myfile["name"];$file_size=$myfile["size"];die($file_type);//连接数据库,把⽂件存到数据库中$conn=mysql_connect("localhost","root","admin");if(!$conn) die("error : mysql connect failed");mysql_select_db("nokiapaymentplat",$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,$conn);//下⾯这句取出了刚才的insert语句的id$id=mysql_insert_id();mysql_close($conn);set_time_limit(30); //恢复缺省超时设置echo "上传成功--- ";echo "<a href='show_info.php?id=$id'>显⽰上传⽂件信息</a>";}else {echo "你没有上传任何⽂件";}>upload.php⽂件如下:<html><head><title>⽂件上传表单</title></head><body><table><form enctype='multipart/form-data' name='myform' action='submit.php' method='post'><INPUT TYPE = "hidden" NAME = "MAX_FILE_SIZE" VALUE ="1000000"><tr><td>选择上传⽂件</td><td><input name='myfile' type='file'></td></tr><tr><td colspan='2'><input name='submit' value='上传' type='submit'></td></tr> </table></body></html>希望本⽂所述对⼤家的PHP程序设计有所帮助。
本文由我司收集整编,推荐下载,如有疑问,请与我司联系如何使用php在mysql数据库中存储图像2014/11/05 87002 How can i store and display the images in a MySQL database. Till now i have only written the code to get the images from the user and store them in a folder, the code that i wrote till now is: HTML FILE 如何在MySQL数据库中存储和显示图像。
直到现在我只编写了代码来从用户那里获取图像并将它们存储在一个文件夹中,我现在写的代码是:HTML FILE input type=“file” name=“imageUpload” id=“imageUpload” PHP FILE PHP文件 $target_dir = “uploads/”;$target_file = $target_dir . basename($_FILES[“imageUpload”][“name”]);$uploadOk = 1;$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);if(move_uploaded_file($_FILES[“imageUpload”][“tmp_name”], $target_file)) { echo “The file “. basename( $_FILES[“imageUpload”][“name”]). “ has been uploaded.”;} else { echo “Sorry, there was an error uploading your file.”;} 4 I found the answer, For those who are looking for the same thing here is how I did it. You should not consider uploading images to the database instead you can store the name of the uploaded file in your database and then retrieve the file name and use it where ever you want to display the image. 我找到了答案,对于那些在寻找同样事物的人来说,我是如何做到的。
上传图⽚保存到MySql数据库并显⽰--经验证有效以下⽅法仅供参考,只是介绍下这⼀种⽅法⽽已。
欢迎指正!!前台(image.html):1<html>2<head>3<title>上传图⽚</title>4</head>5<body>6<form method="post" action="upimage.php" enctype="multipart/form-data"><center><br><br><br><br>7 <input type="hidden" value="204800" name="MAX_FILE_SIZE"/>8 File: <input type="file" name="imgfile" /><br><br>9 <input type="submit" value="OK" name="submitbtn" style="width:100px;height:23px"/></center>10 </form>11</body>12</html>后台处理(upimage.php):1<?php2 //向数据库中插⼊图⽚3 $imgfile=$_FILES['imgfile'];4 $submitbtn=$_POST['submitbtn'];5 if($submitbtn=='OK' and is_array($imgfile))6 {7 $name=$imgfile['name']; //取得图⽚名称8 $type=$imgfile['type']; //取得图⽚类型9 $size=$imgfile['size']; //取得图⽚长度10 $tmpfile=$imgfile['tmp_name']; //图⽚上传上来到临时⽂件的路径11 if($tmpfile and is_uploaded_file($tmpfile)) //判断上传⽂件是否为空,⽂件是不是上传的⽂件12 {13 //读取图⽚流14 $file=fopen($tmpfile,"rb");15 $imgdata=bin2hex(fread($file,$size)); //bin2hex()将⼆进制数据转换成⼗六进制表⽰16 fclose($file);1718 $mysqli=mysql_connect("localhost","root","123456"); //连接数据库函数19 mysql_select_db("test"); //选择数据库20 //插⼊出数据库语句,图⽚数据前要加上0x,⽤于表⽰16进制数21 if(mysql_query("insert into images(name,type,image) values('".$name."','".$type."',0x".$imgdata.")"))22 echo "<center>插⼊成功!<br><br><a href='disimage.php'>显⽰图⽚</a></center>";23 else24 echo "<center>插⼊失败!</center>";25 mysql_close();26 }27 else28 echo "<center>请先选择图⽚!<br><br><a href='image.html'>点此返回</a></center>";29 }30 else31 echo "<center>请先选择图⽚!<br><br><a href='image.html'>点此返回</a></center>";32?>显⽰图⽚(disimage.php):1<?php2 mysql_connect("localhost","root","123456");3 mysql_select_db("test");4 //显⽰最新插⼊的那张图⽚5 $result=mysql_query("select image from images where id=(select max(id) from images)");6 $row=mysql_fetch_object($result);7 header("Content-Type:image/pjpeg");8 echo $row->image;9 mysql_close();10?>。
php图⽚上传存储源码,可实现预览<?phpheader("content-Type: text/html; charset=gb2312");$uptypes=array('image/jpg', //上传⽂件类型列表'image/jpeg','image/png','image/pjpeg','image/gif','image/bmp','application/x-shockwave-flash','image/x-png','application/msword','audio/x-ms-wma','audio/mp3','application/vnd.rn-realmedia','application/x-zip-compressed','application/octet-stream');$max_file_size=10000000; //上传⽂件⼤⼩限制, 单位BYTE$path_parts=pathinfo($_SERVER['PHP_SELF']); //取得当前路径$destination_folder="up/"; //上传⽂件路径$watermark=0; //是否附加⽔印(1为加⽔印,0为不加⽔印);$watertype=1; //⽔印类型(1为⽂字,2为图⽚)$waterposition=2; //⽔印位置(1为左下⾓,2为右下⾓,3为左上⾓,4为右上⾓,5为居中);$waterstring=""; //⽔印字符串$waterimg="xplore.gif"; //⽔印图⽚$imgpreview=1; //是否⽣成预览图(1为⽣成,0为不⽣成);$imgpreviewsize=1/1; //缩略图⽐例?><html xmlns="undefined"><head><title>图⽚上传储存</title><LINK rel="Bookmark" href="/ico.ico" ><LINK rel="Shortcut Icon" href="/ico.ico" /><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><meta name="description" content="亿脑⽹盘_免费⽹络⽆限⼤图⽚上传储存" /><style type="text/css">body,td{font-family:tahoma,verdana,arial;font-size:11px;line-height:15px;background-color:white;color:#666666;strong{font-size:12px;}a:link{color:#0066CC;}a:hover{color:#FF6600;}a:visited{color:#003366;}a:active{color:#9DCC00;}a{TEXT-DECORATION:none}td.irows{height:20px;background:url("index.php?i=dots") repeat-x bottom}</style></head><script type="text/javascript">function oCopy(obj){obj.select();js=obj.createTextRange();js.execCommand("Copy");};function sendtof(url){window.clipboardData.setData('Text',url);alert('复制地址成功,粘贴给你好友⼀起分享。
PHP上传图片代码保存到数据库Html代码:up_logo.html静态页面上传的图片,点击“保存”后跳转到“test.php”。
<form name="theForm" method="post" action="test.php"><table width="100%"><tr><td style="width:30%"> <input type="file" name="file_logo" /></td></tr><tr><td align="center"><input type="submit" value="保存" class="button2" /> <input type="reset" value="重置" class="button2" /></td></tr></table></form>Php代码:test.phpif (!empty($_FILES["file_logo"]["name"])) { //提取文件域内容名称,并判断$path="images/logo/"; //上传路径(可以自行修改)if(!file_exists($path)){//检查是否有该文件夹,如果没有就创建,并给予最高权限mkdir("$path", 0700);}//允许上传的文件格式$tp = array("image/gif","image/pjpeg","image/jpeg","image/png");//检查上传文件是否在允许上传的类型if(!in_array($_FILES["file_logo"]["type"],$tp)){echo "<script>alert('格式不对');history.go(-1);</script>";exit;}//END IF$filetype = $_FILES['file_logo']['type'];if($filetype == 'image/jpeg'){$type = '.jpg';}if ($filetype == 'image/jpg') {$type = '.jpg';}if ($filetype == 'image/pjpeg') {$type = '.jpg';}if($filetype == 'image/gif'){$type = '.gif';}if($filetype == 'image/png'){$type = '.png';}if($_FILES["file_logo"]["name"]){$today=date("YmdHis"); //获取时间并赋值给变量$file2 = $path.$today.$type; //图片的完整路径$img = $today.$type; //图片名称$flag=1;}//END IFif($flag) {$result=move_uploaded_file($_FILES["file_logo"]["tmp_name"],$file2);}//特别注意这里传递给move_uploaded_file的第一个参数为上传到服务器上的临时文件}//这里就可以写sql的语句插入到数据库中Ps:插入图片路径为$file2。
PHP实现图⽚(⽂件)上传这⼏天整理做过的php项⽬,感觉这个经常会⽤到,传上来共享⼀下咯⾸先,前端界⾯1、表单的⾸⾏需要加上enctype="multipart/form-data",需要上传的图⽚必须设置 type="file"表⽰选择⽂件<form id="img_form" method="post" class="form-horizontal" role="form" enctype="multipart/form-data"><label class="col-sm-3 control-label" for="image">图⽚:</label><div class="col-sm-9 require"><input type="hidden" name="MAX_FILE_SIZE" value="2000000">//⽂件最⼤尺⼨<input type="file" class="form-control" name="image" id="image"></div></div></form>2、为表单添加事件,我⽤的是ajax因为图⽚在是⼆进制传输,所以需要⽤new FormData(this)获取表单⾮⽂本类的数据(注包括⽂本类),纯⽂本类数据可⽤$(this).serialize();$('#form1').submit(function (e) {e.preventDefault();var data=new FormData(this);//获取⾮⽂本类的数据$.ajax({url:"php/add.php",//处理页⾯的路径data:data,//通过json格式将⼀组数据传过去type:"post",//数据的提交和传递⽅式,最好⽤POSTdataType:"json",//页⾯返回值的类型,共有三种:TEXT,JSON,XML可选cache:false,contentType:false,processData:false,success:function(res){//回调函数:如果ajax调⽤成功,就执⾏这个success后⾯的函数,(data)当做参数返回过来if (res.flag===1){alert('上传成功!');} else if(res.flag===2){alert('⽹络或其他未知错误,请重试!')}else{alert('图⽚格式错误,请重试!')}},error: function () {alert("error")}});});3、编写php⽂件connect.php数据库连接⽂件<?php$link=new PDO("mysql:host=localhost;port=3306;dbname=db","root","");$link->query("set names utf8");add.phpextract($_POST):批量获取前端post⽅式传过来的数据,使⽤参数时参数名为前端传过来的初始名。
1. <?php2. session_start();3. /*4. Pro上传产品图片5. 2012-07-316. 里面带有图片剪切、及加图片水印7. */8. include_once 'gjbs_conn.php'; //数据库连接9. ?>10. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />11. <?php12. //判断13. if(@is_uploaded_file($_FILES['upPic']['tmp_name'])){14. $upPic = $_FILES['upPic'];15. $up_name = $upPic['name'];16. $up_type = $upPic['type'];17. $up_size = $upPic['size'];18. $up_tmp_name = $upPic['tmp_name'];19. $up_error = $upPic['error'];20.21. //判断上传格式22. switch ($up_type){23. case 'image/jpeg':24. $ok = '1';25. break;26.27. case 'image/jpg':28. $ok = '1';29. break;30.31. case 'image/pjpeg':32. $ok = '1';33. break;34.35. case 'image/png':36. $ok = '1';37. break;38. }39.40. date_default_timezone_set("ETC/GMT-8");41. $newsname = date('YmdHis').mt_rand().'.jpg';42. //判断上传东西43. //图片格式44. if($ok != '1'){45. echo "<script>alert('上传失败:无法识别图片格式,请上传.jpg/.png格式的图片!!请刷新该页面!');location='gjbs_up_pro.php';</script>";46. exit();47. }48. //判断上传图片大小49. if($up_size >= '1000000'){50. echo "<script>alert('上传失败:图片大小超过1M[请联系系统管理员]!!');location='gjbs_up_pro.php';</script>";51. exit();52. }else{53. move_uploaded_file($up_tmp_name,"upPic/".$newsname);54.55. #--------------------------------------------------------------------------------------56. $image = "upPic/".$newsname;57. $img=getimagesize($image);58. #$aaa=$img[0];59. #$aaa-=220; //水印位置60. #$bbb=$img[1];61. #$bbb-=89; //水印位置高度62. $aaa=ceil($img[0]/2);63. $aaa-=110;64. $bbb=ceil($img[1]/2);65. $bbb-=55;66. switch($img[2]){67. case 1:68. $im =@imagecreatefromgif($image);69. break;70. case 2:71. $im =@imagecreatefromjpeg($image);72. break;73. case 3:74. $im =@imagecreatefrompng($image);75. break;76. }77.78.79. $logo = "logosy.png";80. $ing=getimagesize($logo);81. $ing =@imagecreatefrompng($logo);82.83. //图片水印84. // 原图片,水印图片,原图x,原图y,水印x,水印y;85. imagecopy($im,$ing,$aaa,$bbb,0,0,'220','110');86.87.88. //文字水印89. $te = imagecolorallocate($im,100,100,100);90. $str =iconv("gbk","utf-8","ZANTEC"); //绘制的中文文字91. //logosy.png92.93. //imagettftext($im,12,0,$aaa,$bbb,$te,'wryh.ttf',$str);94.95. //剪切图片96. $aba = $img[0];97. $bab = $img[1];98. $abab =($aba/$bab);99. //$abab=(int)$abab;100. $abab=ceil(500/$abab);101. //$abab=(int)$abab;102.103. $new=imagecreatetruecolor(500,$abab);104. imagecopyresized($new,$im,0,0,0,0,500,$abab,$img[0],$img[1]); 105.106. //header("Content-type:image/jpeg");107. //header("Content-type:image/png");108. //imagepng($ing);109. //imagejpeg($im,'upPicc/aa.jpg');110. imagejpeg($new,'upPic_b/'.$newsname);111.112.113.114. //剪切图片115. $abab =($aba/$bab);116. //$abab=(int)$abab;117. $abab=ceil(160/$abab);118. $new1=imagecreatetruecolor(160,$abab);119. imagecopyresized($new1,$im,0,0,0,0,160,$abab,$img[0],$img[1]);120. //imagejpeg($new);121. imagejpeg($new1,'upPic_s/'.$newsname);122. #--------------------------------------------------------------------------------------123. echo "<script>alert('上传成功!!');</script>";124. $_SESSION['uppicname'] = $newsname; // 把SESSION['uppicname'] 存在数据库125. }126. //执行移动127.128.129. }130. ?>131. <style type="text/css">132. body {133. margin-left: 0px;134. margin-top: 0px;135. background-color:#09F;136. }137. </style>138. <form enctype="multipart/form-data" method="post" name="upform">139. 上传图片:<input name="upPic" type="file"/>140. <input name="submit" type="submit" value="上传" />141. </form>。
这篇文章主要介绍了php实现上传图片保存到数据库的方法,可通过将图片保存在数据库实现多台服务器共享文件的功能,非常具有实用价值,需要的朋友可以参考下php实现上传图片保存到数据库的方法。
分享给大家供大家参考。
具体分析如下:
php 上传图片,一般都使用move_uploaded_file方法保存在服务器上。
但如果一个网站有多台服务器,就需要把图片发布到所有的服务器上才能正常使用(使用图片服务器的除外)如果把图片数据保存到数据库中,多台服务器间可以实现文件共享,节省空间。
首先图片文件是二进制数据,所以需要把二进制数据保存在mysql数据库。
mysql数据库提供了BLOB类型用于存储大量数据,BLOB是一个二进制对象,能容纳不同大小的数据。
BLOB类型有以下四种,除存储的最大信息量不同外,其他都是一样的。
可根据需要使用不同的类型。
TinyBlob 最大255B
Blob 最大65K
MediumBlob 最大16M
LongBlob 最大4G
数据表photo,用于保存图片数据,结构如下:
代码如下:
CREATE TABLE `photo` (
`id` int(10) unsigned NOT NULL auto_increment,
`type` varchar(100) NOT NULL,
`binarydata` mediumblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
upload_image_todb.php:
代码如下:
<?php
// 连接数据库
","") or die(mysql_error());
@mysql_select_db('demo',$conn) or die(mysql_error());
// 判断action
$action = isset($_REQUEST['action'])? $_REQUEST['action'] : '';
// 上传图片
if($action=='add'){
$image = mysql_escape_string(file_get_contents($_FILES['photo']['tmp_name']));
$type = $_FILES['photo']['type'];
$sqlstr = "insert into photo(type,binarydata) values('".$type."','".$image."')";
@mysql_query($sqlstr) or die(mysql_error());
header('location:upload_image_todb.php');
exit();
// 显示图片
}elseif($action=='show'){
$id = isset($_GET['id'])? intval($_GET['id']) : 0;
$sqlstr = "select * from photo where id=$id";
$query = mysql_query($sqlstr) or die(mysql_error());
$thread = mysql_fetch_assoc($query);
if($thread){
header('content-type:'.$thread['type']);
echo $thread['binarydata'];
exit();
}
}else{
// 显示图片列表及上传表单
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title> upload image to db demo </title>
</head>
<body>
<form name="form1" method="post" action="upload_image_todb.php" enctype="multipart/form-data">
<p>图片:<input type="file" name="photo"></p>
<p><input type="hidden" name="action" value="add"><input type="submit" name="b1" value="提交"></p>
</form>
<?php
$sqlstr = "select * from photo order by id desc";
$query = mysql_query($sqlstr) or die(mysql_error());
$result = array();
while($thread=mysql_fetch_assoc($query)){
$result[] = $thread;
}
foreach($result as $val){
echo '<p><img src="upload_image_todb.php?action=show&id='.$val['id'].'&t='.time().'"
width="150"></p>';
}
?>
</body>
</html>
<?php
}
?>
希望本文所述对大家的php程序设计有所帮助。
更多信息请查看IT技术专栏。