php实现上传图片保存到数据库的方法
用纯ASP代码实现图片上传到指定文件夹并存入数据库中的代码

用纯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上传图⽚到数据库并显⽰的实例代码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上传图片的代码并保存到数据库

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实现图片上传的方法

两种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实现的获取网页中的图片并保存到本地的代码用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中的方法

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⽅式上传图⽚⽂件功能⽰例本⽂实例讲述了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内置的系统函数,如果使⽤过程中出现问题,建议查看是否启⽤相应的系统函数。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
这篇文章主要介绍了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技术专栏。