本文目录一览:
用php写一个上传图片的程序 谢谢
?php
$uptypes=array('image/jpg', //上传文件类型列表
'image/jpeg',
'image/png',
'image/pjpeg',
'image/gif',
'image/bmp',
'application/x-shockwave-flash',
'image/x-png');
$max_file_size=5000000; //上传文件大小限制, 单位BYTE
$destination_folder="upload/"; //上传文件路径
$watermark=0; //是否附加水印(1为加水印,其他为不加水印);
$watertype=1; //水印类型(1为文字,2为图片)
$waterposition=1; //水印位置(1为左下角,2为右下角,3为左上角,4为右上角,5为居中);
$waterstring="newphp.site.cz"; //水印字符串
$waterimg="xplore.gif"; //水印图片
$imgpreview=1; //是否生成预览图(1为生成,其他为不生成);
$imgpreviewsize=1/2; //缩略图比例
?
html
head
titleM4U BLOG - fywyj.cn/title
meta http-equiv="Content-Type" content="text/html; charset=gb2312"
style type="text/css"body,td{font-family:tahoma,verdana,arial;font-size:11px;line-height:15px;background-color:white;color:#666666;margin-left:20px;}
strong{font-size:12px;}
aink{color:#0066CC;}
a:hover{color:#FF6600;}
aisited{color:#003366;}
a:active{color:#9DCC00;}
table.itable{}
td.irows{height:20px;background:url("index.php?i=dots" repeat-x bottom}/style
/head
body
centerform enctype="multipart/form-data" method="post" name="upform"
上传文件: brbrbr
input name="upfile" type="file" style="width:200;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="17"
input type="submit" value="上传" style="width:30;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="17"brbrbr
允许上传的文件类型为:jpg|jpeg|png|pjpeg|gif|bmp|x-png|swf brbr
a href="index.php"返回/a
/form
?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!is_uploaded_file($_FILES["upfile"][tmp_name]))
//是否存在文件
{
echo "font color='red'文件不存在!/font";
exit;
}
$file = $_FILES["upfile"];
if($max_file_size $file["size"])
//检查文件大小
{
echo "font color='red'文件太大!/font";
exit;
}
if(!in_array($file["type"], $uptypes))
//检查文件类型
{
echo "font color='red'只能上传图像文件或Flash!/font";
exit;
}
if(!file_exists($destination_folder))
mkdir($destination_folder);
$filename=$file["tmp_name"];
$image_size = getimagesize($filename);
$pinfo=pathinfo($file["name"]);
$ftype=$pinfo[extension];
$destination = $destination_folder.time().".".$ftype;
if (file_exists($destination) $overwrite != true)
{
echo "font color='red'同名文件已经存在了!/a";
exit;
}
if(!move_uploaded_file ($filename, $destination))
{
echo "font color='red'移动文件出错!/a";
exit;
}
$pinfo=pathinfo($destination);
$fname=$pinfo[basename];
echo " font color=red已经成功上传/fontbr文件名: font color=blue".$destination_folder.$fname."/fontbr";
echo " 宽度:".$image_size[0];
echo " 长度:".$image_size[1];
if($watermark==1)
{
$iinfo=getimagesize($destination,$iinfo);
$nimage=imagecreatetruecolor($image_size[0],$image_size[1]);
$white=imagecolorallocate($nimage,255,255,255);
$black=imagecolorallocate($nimage,0,0,0);
$red=imagecolorallocate($nimage,255,0,0);
imagefill($nimage,0,0,$white);
switch ($iinfo[2])
{
case 1:
$simage =imagecreatefromgif($destination);
break;
case 2:
$simage =imagecreatefromjpeg($destination);
break;
case 3:
$simage =imagecreatefrompng($destination);
break;
case 6:
$simage =imagecreatefromwbmp($destination);
break;
default:
die("font color='red'不能上传此类型文件!/a");
exit;
}
imagecopy($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);
imagefilledrectangle($nimage,1,$image_size[1]-15,80,$image_size[1],$white);
switch($watertype)
{
case 1: //加水印字符串
imagestring($nimage,2,3,$image_size[1]-15,$waterstring,$black);
break;
case 2: //加水印图片
$simage1 =imagecreatefromgif("xplore.gif");
imagecopy($nimage,$simage1,0,0,0,0,85,15);
imagedestroy($simage1);
break;
}
switch ($iinfo[2])
{
case 1:
//imagegif($nimage, $destination);
imagejpeg($nimage, $destination);
break;
case 2:
imagejpeg($nimage, $destination);
break;
case 3:
imagepng($nimage, $destination);
break;
case 6:
imagewbmp($nimage, $destination);
//imagejpeg($nimage, $destination);
break;
}
//覆盖原上传文件
imagedestroy($nimage);
imagedestroy($simage);
}
if($imgpreview==1)
{
echo "br图片预览:br";
echo "a href=\"".$destination."\" target='_blank'img src=\"".$destination."\" width=".($image_size[0]*$imgpreviewsize)." height=".($image_size[1]*$imgpreviewsize);
echo " alt=\"图片预览:\r文件名:".$destination."\r上传时间:\" border='0'/a";
}
}
?
/center
/body
/html
PHP上传图片代码
兄弟用这个吧
我不知道你的数据库是什么样的就随便弄了一个:
希望对你有用,名字采用时间的格式命名的:
?
include("../inc.php");
function getname($exname){
$dir = "upload/";
//目录名,可以自己改
$i=1;
//文件的名称前缀,本例默认从1开始依次加加
$showtime=date("YmdHis");
if(!is_dir($dir)){
mkdir($dir,0777);
//如果不存在此目录,则创建,请保证您有相应的权限
}
while(true){
if(!is_file($dir.$showtime.".".$exname)){
$name=$showtime.".".$exname;
break;
}
}
return $dir.$name;
}
$max=$_POST["MAX_FILE_SIZE"];
if($max($_FILES['upfile']['size']))
echo "script alert('文件大于2000000b!');history.back();/script";
$exname=strtolower(substr($_FILES['upfile']['name'],(strrpos($_FILES['upfile']['name'],'.')+1)));//返回文件后缀名
if($exname=="jpg"||$exname=="bmp"||$exname=="jpeg"||$exname=="gif"){
$uploadfile = getname($exname);
$add=$uploadfile;
$name=$_POST["name"];
$time=$_POST["time"];
if($name=="")
echo "script alert('标题不能为空!');history.back();/script";
else
{
$sql = "INSERT INTO `web`.`pto` (
`ID` ,
`name` ,
`add` ,
`time`
)
VALUES (
null, '".$name."', '".$add."', '".$time."'
)";
mysql_query($sql) or die("写失败");
if (move_uploaded_file($_FILES['upfile']['tmp_name'], $uploadfile))
{
echo "script alert('文件上传成功!');window.location.href('pto.php');/script";
}else {
echo "script alert('文件上传失败!');history.back();/script";
}
} }
else
echo "script alert('文件格式错误!');history.back();/script";
?
php上传图片到服务器的前端和php代码
前端 代码 使用 extjs 3.4
uploadPhotoWindow=Ext.extend(Ext.Window,{
title:" 上传图片 Upload Photo",
height:420 ,
width:600,
closeAction:'close',
modal : true,
iconCls:'btn-setting',
buttonAlign: 'center',
upload_ok:false,
haveUpload:false,
initComponent : function() {
Ext.form.Field.prototype.msgTarget = 'side';
var po_no=new Ext.form.TextField({name:'Po_no',fieldLabel: '单号 Po No',itemId:'Po_no', width:120,
allowBlank: false, value:this.cur_sele_po_no, hidden:true});
var OP=new Ext.form.TextField({name:'OP',itemId:'OP', width:12,
allowBlank: false, value:"uploadphoto", hidden:true});
var file_name=new Ext.form.TextField({name:'photo_file_name',itemId:'photo_file_name', width:180,
allowBlank: false, value:"",hidden:true,});
var imagebox = new Ext.BoxComponent({
itemId:'imagebox',
autoEl: {
tag: 'img', //指定为img标签
style: 'height:100%;margin:0px auto;border:1px solid #ccc; text-align:center;margin-bottom:10px',
src: 'img/userimg/nophoto.jpg' , //指定url路径
}
});
var form_set_field = new Ext.FormPanel({
frame:true,
itemId:'form_set_field',
layout:'form',
//tableAttrs: {border: 1},
defaults:{labelAlign:'right',labelWidth:110,bodyStyle: 'padding:0 30px 0 0;',frame:false,layout:'form'},
items:[po_no,OP,file_name,imagebox],
});
var file = new Ext.form.TextField({
name: 'imgFile',
fieldLabel: '文件上传',
inputType: 'file',
allowBlank: false,
blankText: '请浏览图片'
});
var form_set_file = new Ext.FormPanel({
frame:true,
fileUpload: true,
itemId:'form_set_file',
layout:'form',
//tableAttrs: {border: 1},
defaults:{labelAlign:'right',labelWidth:110,bodyStyle: 'padding:0 30px 0 0;',frame:false,layout:'form'},
items:[file],
});
var btnOK= new Ext.Button({text: '上传 Upload ', iconCls:'btn-save',width:70,handler: function(){
var form_set=this.ownerCt.ownerCt.getComponent('form_set_file');
var form_set_field=this.ownerCt.ownerCt.getComponent('form_set_field');
var po_no=form_set_field.getComponent('Po_no').getValue();
var file_name=form_set_field.getComponent('photo_file_name');
//alert(po_no);
var imgbox=form_set_field.getComponent('imagebox');
if (form_set.getForm().isValid()){
form_set.getForm().submit({
waitMsg : '正在上传数据 Uploading....',waitTitle:'请稍候 waiting....',
url:'php/toolsfile/photoUpload.php',
method : 'post',
success : function(form, action){
var out = action.result.success;
if (out != true){
Ext.Msg.alert('提示 Tips ', '上传数据失败,错误信息 Save failure :'+action.result.msg);
//alert(action.result.msg);
} else{
//Ext.Msg.alert('提示 Tips ', '上传数据成功,服务器信息: Save success '+action.result.msg);
file_name.setValue(action.result.file_name);
imgbox.getEl().dom.src=action.result.file_scr;
form_set.ownerCt.savePhoto();
//form_set.ownerCt.grid.store.load();
//form_set.ownerCt.dateChang=true;
//form_set.ownerCt.destroy( );
}
},
failure: function(form, action) {
switch (action.failureType) {
case Ext.form.Action.CLIENT_INVALID:
Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
break;
case Ext.form.Action.CONNECT_FAILURE:
Ext.Msg.alert('Failure', 'Ajax communication failed');
break;
case Ext.form.Action.SERVER_INVALID:
Ext.Msg.alert('Failure', action.result.msg);
break;
}
},
});
}else{
Ext.Msg.alert('提示 Tips :', '请选择文件! \n Please select Img file ');
}
}
});
var btnCancel = new Ext.Button({text: ' 关闭 Close ', iconCls:'btn-cancel',width:70,handler: function(){this.ownerCt.ownerCt.destroy( )}});
Ext.apply(this,{
items: [form_set_field,form_set_file],
buttons: [btnOK, btnCancel],
});
uploadPhotoWindow.superclass.initComponent.call(this);
},
savePhoto:function (){
//alert(this.cur_sele_po_no);
var form_set_field=this.getComponent('form_set_field');
var form_set_file=this.getComponent('form_set_file');
form_set_field.getForm().submit({
waitMsg : '上传成功,正在存储 saveing....',waitTitle:'请稍候 waiting....',
url:'php/jsonfile/po_nophotolist_json.php',
method : 'post',
success : function(form, action){
var out = action.result.success;
if (out != true){
Ext.Msg.alert('提示 Tips ', '存储失败,错误信息 Save failure :'+action.result.msg);
} else{
Ext.Msg.alert('提示 Tips ', '存储成功,服务器信息: Save success '+action.result.msg);
form_set_file.getForm().reset();
form_set_file.ownerCt.haveUpload=true;
}
},
failure: function(form, action) {
switch (action.failureType) {
case Ext.form.Action.CLIENT_INVALID:
Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
break;
case Ext.form.Action.CONNECT_FAILURE:
Ext.Msg.alert('Failure', 'Ajax communication failed');
break;
case Ext.form.Action.SERVER_INVALID:
Ext.Msg.alert('Failure', action.result.msg);
break;
}
},
});
},
isUpload:function(){
return this.haveUpload;
}
});
后台php photoUpload.php'
?
require_once('../classfile/guid.class.php');
if(!isset($_FILES['imgFile'])){
echo json_encode(array("success"=false, 'msg'="Not get Imgfile"));
return;
}
$upfile=$_FILES['imgFile'];
$name=$upfile["name"];//上传文件的文件名
$type=$upfile["type"];//上传文件的类型
$size=$upfile["size"];//上传文件的大小
$tmp_name=$upfile["tmp_name"];//上传文件的临时存放路径
$error_cod=$upfile["error"];
if ($error_cod0){
echo json_encode(array("success"=false, 'msg'=$error_cod));
}
$ext_file_name="";
switch ($type){
case 'image/pjpeg':
$okType=true;
$ext_file_name =".jpg";
break;
case 'image/jpeg':
$okType=true;
$ext_file_name =".jpg";
break;
case 'image/gif':
$okType=true;
$ext_file_name =".gif";
break;
case 'image/png':
$okType=true;
$ext_file_name =".png";
break;
}
if(!$okType){
echo json_encode(array("success"=false, 'msg'="Not image "));
return;
}
$web_root="D:".DIRECTORY_SEPARATOR."Easy2PHP5".DIRECTORY_SEPARATOR."webSiteJfz".DIRECTORY_SEPARATOR;
$photo_tmp_path=$web_root."img".DIRECTORY_SEPARATOR."userimg".DIRECTORY_SEPARATOR."temp";
$temp_file_name= creat_guid(0).$ext_file_name;
$photo_tmp_file_name=$photo_tmp_path.DIRECTORY_SEPARATOR.$temp_file_name;
$photo_tmp_file_scr="img".DIRECTORY_SEPARATOR."userimg".DIRECTORY_SEPARATOR."temp".DIRECTORY_SEPARATOR.$temp_file_name;
move_uploaded_file($tmp_name,$photo_tmp_file_name);
echo json_encode(array("success"=true, 'msg'= "ok","file_name"=$photo_tmp_file_name,"file_scr"=$photo_tmp_file_scr));
//echo json_encode(array("success"=false, 'msg'= json_encode($_FILES['imgFile'])));
return;
?
guid.class.php // 生成唯一的图片文件名
?
function creat_guid($long){
$uuid="";
if (function_exists('com_create_guid')){
$uuid=com_create_guid();
}else{
mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
$charid = strtoupper(md5(uniqid(rand(), true)));
$hyphen = chr(45);// "-"
$uuid = chr(123)// "{"
.substr($charid, 0, 8).$hyphen
.substr($charid, 8, 4).$hyphen
.substr($charid,12, 4).$hyphen
.substr($charid,16, 4).$hyphen
.substr($charid,20,12)
.chr(125);// "}"
//return $uuid;
}
if (!isset($long) || $long==0 ){
return substr($uuid,1, strlen($uuid)-2);
}else{
return $uuid;
}
}
怎样用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
// 连接数据库
$conn=@mysql_connect("localhost","root","") 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
pinput 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 'pimg
src="upload_image_todb.php?action=showid='.$val['id'].'t='.time().'"
width="150"/p';
}
?
/body
/html
?php
}
?
程序运行截图和数据库截图: