导航:首页 > 编程语言 > phpuploadimage

phpuploadimage

发布时间:2022-04-21 18:39:50

1. php图片上传 保存 及 显示问题

这段代码里没有 上传文件的的路径代码
应该有 文件要保存到的文件夹路径 忘了把那个路径插入到数据库里
显示出来的时候从数据库把路径调用出来接上图片名在img的 src上就行了
具体代码呢 参考一下 下面的代码吧
==========================================
<?php

/**
*********************************************
参数设定
*********************************************
**/
//最大上传文件大小
$MAX_SIZE = 20000000;
//设置Mine类型
$FILE_MIMES = array

('image/jpeg','image/jpg','image/gif','image/png','applicat

ion/msword');
//设置允许上传的文件类型,按照格式添加
$FILE_POSTFIX = array

('.zip','.jpg','.png','.gif','.wma','.rm','.wmv','.doc','.m

peg','.mp3','.avi');
//是否允许删除以上传的文件,允许:yes; 不允许:no;
$DELETE_ENABLE = 'yes';

/**
*********************************************
变量设定
*********************************************
**/
$site_name = $_SERVER['HTTP_HOST'];
$site_url = "http://".$site_name.dirname($_SERVER

['PHP_SELF']);
$site_this = "http://".$site_name.$_SERVER['PHP_SELF'];
//可见性,为0时只有会员可见,为1时所有人员都可见
$visibility = true;
if($visibility)
{
$upload_dir = "upload/public/";
}else
{
$upload_dir = "upload/private/";
}
$upload_url = $site_url."/".$upload_dir;

/**
*********************************************
创建上传目录
*********************************************
**/
if(!is_dir($upload_dir))
{
if(!mkdir($upload_dir))
die('文件没有创建成功!!');
if (!chmod($upload_dir,0777))
die ("改变权限失败.");
}
/**
*********************************************
删除文件处理
*********************************************
**/

if($del && $DELETE_ENABLE == 'yes')
{
$resourse = fopen('log.txt','a');
fwrite($resourse,date('Y-m-d H:i:s')."删除 - 删除操

作的ip地址为: $_SERVER[REMOTE_ADDR]"
.$del."\n");
$result = unlink($del);
if(!$result)
{
echo "删除操作失败,请重试";
echo "<meta http-equiv=\"refresh\"

content=\"1;url=upload.php\">";
exit;
}else
{
echo "删除操作成功!返回";
echo "<meta http-equiv=\"refresh\"

content=\"1;url=upload.php\">";
exit;
}
}
/**
*********************************************
上传文件处理
*********************************************
**/
if($_FILES['userfile'])
{
$resourse = fopen('log.txt','a');
fwrite($resourse,date('Y-m-d H:i:s')."上传 - 上传操

作的ip地址为: $_SERVER[REMOTE_ADDR]"
.$_FILES['userfile']['name']."

".$_FILES['userfile']['type']."\n");
fclose($resourse);
$file_name = $_FILES['userfile']['name'];//上传文件

的名称
$file_type = $_FILES['userfile']['type'];//上传文件

的类型
$file_postfix = substr($file_name,strrpos

($file_name,"."));//上传文件的后缀
//文件大小检查
if($_FIFES['userfile']['size'] > $MAX_SIZE)
{
echo '文件太大不能上传';

}elseif(!in_array($file_type,$FILE_MIMES) && !

in_array($file_postfix,$FILE_POSTFIX))
{
echo "对不起你所上传的文件类型不符合规定,

不允许上传!!";
}else
{
do_upload($upload_dir,$upload_url);
}
}

?>
<html>
<head>
<title>资料管理</title>
<meta http-equiv="Content-Type" content="text/html;

charset=gb2312">
<style type="text/css">
<!--
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
.样式1 {
font-size: 14px;
color: #FFFFFF;
font-weight: bold;
}
.样式2 {font-size: 12px}
.样式3 {
color: #FF0000;
font-weight: bold;
font-size: 12px;
}
.样式4 {
color: #FFFFFF;
font-weight: bold;
}
.样式6 {
font-size: 12px;
color: #FFFFFF;
font-weight: bold;
}
.样式7 {
color: #FF0000;
font-weight: bold;
}
-->
</style></head>

<body>
<table width="100%" border="0" cellspacing="0">
<tr bgcolor="#6699FF">
<td height="19" colspan="2"><div align="center"><span

class="样式1">资 料 管 理</span></div></td>
</tr>
<tr>
<td height="15" colspan="2"></td>
</tr>
<tr bgcolor="#6699FF">
<td height="16" colspan="2"><span class="样式2"><span

class="样式7">-></span><span class="样式4"> 资料上传

</span></span></td>
</tr>
<tr bgcolor="#CCCCCC">
<td height="25" colspan="2">
<form name="upload" id="upload"

ENCTYPE="multipart/form-data" method="post" action

="./upload.php">
<span class="样式2">上传文件</span>
<input type="file" id="userfile" name="userfile">
<input type="submit" name="upload" value="上传">
</form></td>
</tr>
<tr bgcolor="#6699FF">
<td colspan="2"><span class="样式3">-></span><span

class="样式6"> 资料更改</span></td>
</tr>
<tr bgcolor="#CCCCCC">
<td colspan="2"><div align="center" class="样式2">资料

列表</div></td>
</tr>
<tr>
<td height="37" colspan="2" bgcolor="#CCCCCC">

<table width="100%" border="0" cellspacing="0">
<tr bgcolor="#6699FF">
<td width="39%"><span class="样式2">文件名

</span></td>
<td width="18%"><span class="样式2">大小

</span></td>
<td width="25%"><span class="样式2">上传时间

</span></td>
<td width="18%"><span class="样式2">操作

</span></td>
</tr>
<?
/**
*********************************************
创建上传目录
*********************************************
**/
$handle = opendir($upload_dir);
while($file = readdir($handle))
{
if(!is_dir($file) && !is_link($file))
{
?>
<tr>
<td><span class="样式2">
<img src='<?=$upload_dir.$file?>'><?=$file?></a>
</span></td>
<td><span class="样式2">
<?=filesize($upload_dir.$file)?>
byte</span></td>
<td><span class="样式2">
<?=date("Y-m-d H:i:s", filemtime

($upload_dir.$file))?>
</span></td>
<td><a href='?del=<?=$upload_dir.$file?>'

title='delete' class="样式2">删除</a></td>
</tr>
<?
}
}
?>
<tr>
<td><span class="样式2"></span></td>
<td><span class="样式2"></span></td>
<td><span class="样式2"></span></td>
<td><span class="样式2"></span></td>
</tr>
</table></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
<?php
function do_upload($upload_dir,$upload_url)
{
$temp_name = $_FILES['userfile']['tmp_name'];
$file_name = $_FILES['userfile']['name'];
$file_name = str_replace("\\","",$file_name);
$file_name = str_replace("'","",$file_name);
$file_path = $upload_dir.$file_name;
//文件名检查
if($file_name = '')
{
echo "文件名无效!!!";
exit;
}
$result = move_uploaded_file

($temp_name,$file_path);
if($result)
{
echo "上传成功!!";
echo "<meta http-equiv=\"refresh\"

content=\"1;url=upload.php\">";
exit;
}else
{
echo "上传失败!!";
echo "<meta http-equiv=\"refresh\"

content=\"1;url=upload.php\">";
exit;
}
echo "end";
}

?>

2. php 异步上传图片几种方法总结

代码如下
form action="upload.php" id="form1" name="form1" enctype="multipart/form-data" method="post" target="uploadIframe"> <!--上传图片页面 --> </form> <iframe name="uploadIframe" id="uploadIframe" style="display:none"></iframe>
然后后台处理完上传图片逻辑后返回给前台,利用ajax修改当前页面DOM对象实现无刷新上传图片的友好功能。
实例
代码如下
a.html <form enctype="multipart/form-data" action="a.php" target="ifram_sign" method="POST"> <input name="submit" id="submit" value="" type="hidden"> <label>上传文件: <input name="test_file" type="file" id="test_file" size="48"></label> <input type="image" value="立即上传" id="submit_btn"> </form><iframe name="ifram_sign" src="" frameborder="0" height="0" width="0" marginheight="0" marginwidth="0"></iframe>
php代码:
代码如下
<?php
if ($_files["test_file"]["error"] > 0)
{
echo "Error: " . $_files["test_file"]["error"] . "<br />";
}
else
{
//这里的判断图片属性的方法就不写了。自己扩展一下。
$filetype=strrchr($_files["test_file"]["name"],".");
$filetype=substr($filetype,1,strlen($filetype));
$filename="img/".time("YmdHis").".".$filetype;
move_uploaded_file($_files["test_file"]["tmp_name"],$filename);
echo '<script >alert(1)</script>';
$return="parent.document.getElementByIdx_x('mpic".$pageset_id."').innerhtml='".$dataimgpath."'";
echo "<script >alert('上传成功')</script>";
echo "<script>{$return}</script>";
}
?>
其实jquery ajax图片异步上传
html:
<!DOCTYPE html PUBLIC "-//W3C//dtd Xhtml 1.0 transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en_US" xml:lang="en_US">
<head>
<title>图片异步上传</title>
</head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<link type="text/css" rel="stylesheet" href="css/index.css">
<body>
<div class="frm">
<form name="uploadFrom" id="uploadFrom" action="upload.php" method="post" target="tarframe" enctype="multipart/form-data">
<input type="file" id="upload_file" name="upfile">
</form>
<iframe src="" width="0" height="0" style="display:none;" name="tarframe"></iframe>
</div>
<div id="msg">
</div>
</body>
</html>

index.js
$(function(){
$("#upload_file").change(function(){
$("#uploadFrom").submit();
});
});

function stopSend(str){
var im="<img src='upload/images/"+str+"'>";
$("#msg").append(im);
}

upload.php
<?php
$file=$_files['upfile'];
$name=rand(0,500000).dechex(rand(0,10000)).".jpg";
move_uploaded_file($file['tmp_name'],"upload/images/".$name);
//调用iframe父窗口的js 函数
echo "<script>parent.stopSend('$name')</script>";
?>

异步上传图片几种方法

3. 高分求thinkphp中设置xheditor图片上传详细步骤。。。

  1. 先在页面上面配置获取网络配置文件地址:window.UEDITOR_CONFIG.serverUrl = xx;

  2. 后面的就是服务器端了


  3. namespaceAdminController;
    useAdminServiceBaseService;

    {
    publicfunction_empty(){
    $action=I('get.action','','htmlspecialchars');
    $callback=I('get.callback');
    $result=null;
    switch($action){
    case'config':
    $result=json_encode($this->_Config());
    break;

    /*上传图片*/
    case'uploadimage':
    /*上传涂鸦*/
    case'uploadscrawl':
    /*上传视频*/
    case'uploadvideo':
    /*上传文件*/
    case'uploadfile':
    $result=$this->_Upload($action);
    break;

    /*列出图片*/
    case'listimage':
    /*列出文件*/
    case'listfile':
    $result=$this->_list($action);
    break;
    /*抓取远程文件*/
    case'catchimage':
    $result=$this->_crawler();
    break;

    default:
    $result=json_encode(array(
    'state'=>'请求地址出错'
    ));
    break;
    }

    if(isset($_GET["callback"])){
    if(preg_match("/^[w_]+$/",$_GET["callback"])){
    echohtmlspecialchars($_GET["callback"]).'('.$result.')';
    }else{
    echojson_encode(array(
    'state'=>'callback参数不合法'
    ));
    }
    }else{
    echo$result;
    }
    }
    privatefunction_Config(){
    $CONFIG=json_decode(preg_replace("//*[sS]+?*//","",file_get_contents(APP_PATH.'Admin/Conf/config.json')),true);
    $CONFIG['imageMaxSize']=UPLOAD_IMAGE_SIZE;
    $CONFIG['scrawlMaxSize']=UPLOAD_IMAGE_SIZE;
    $CONFIG['catcherMaxSize']=UPLOAD_IMAGE_SIZE;
    $CONFIG['videoMaxSize']=UPLOAD_VIDEO_SIZE;
    $CONFIG['fileMaxSize']=UPLOAD_FILE_SIZE;
    $CONFIG['scrawlUrlPrefix']=ATTACH_URL;
    $CONFIG['imageUrlPrefix']=ATTACH_URL;
    $CONFIG['snapscreenUrlPrefix']=ATTACH_URL;
    $CONFIG['catcherUrlPrefix']=ATTACH_URL;
    $CONFIG['videoUrlPrefix']=ATTACH_URL;
    $CONFIG['fileUrlPrefix']=ATTACH_URL;
    $CONFIG['imageManagerUrlPrefix']=ATTACH_URL;
    $CONFIG['fileManagerUrlPrefix']=ATTACH_URL;
    return$CONFIG;
    }
    privatefunction_Upload($action){
    $config=$this->_Config();
    $up=newLibExtendUpload();
    $type='';
    switch($action){
    case'uploadimage':
    $fieldName=$config['imageFieldName'];
    $type='image';
    break;
    case'uploadscrawl':
    $fieldName=$config['scrawlFieldName'];
    $type='base64';
    break;
    case'uploadvideo':
    $fieldName=$config['videoFieldName'];
    $type='video';
    break;
    case'uploadfile':
    default:
    $fieldName=$config['fileFieldName'];
    $type='file';
    break;
    }
    if($type=='base64'){
    $result=$up->saveBase64($fieldName);
    }else{
    $result=$up->save($fieldName,$type);
    }
    returnjson_encode($result);
    }
    privatefunction_list($action){
    $config=$this->_Config();
    switch($action){
    /*列出文件*/
    case'listfile':
    $allowFiles=$config['fileManagerAllowFiles'];
    $listSize=$config['fileManagerListSize'];
    break;
    /*列出图片*/
    case'listimage':
    default:
    $allowFiles=$config['imageManagerAllowFiles'];
    $listSize=$config['imageManagerListSize'];
    }
    $allowFiles=substr(str_replace(".","|",join("",$allowFiles)),1);

    /*获取参数*/
    $size=isset($_GET['size'])?htmlspecialchars($_GET['size']):$listSize;
    $start=isset($_GET['start'])?htmlspecialchars($_GET['start']):0;
    $end=$start+$size;

    /*获取文件列表*/
    $path=UPLOAD_PATH;
    $files=$this->_getfiles($path,$allowFiles);
    if(!count($files)){
    returnjson_encode(array(
    "state"=>"nomatchfile",
    "list"=>array(),
    "start"=>$start,
    "total"=>count($files)
    ));
    }

    /*获取指定范围的列表*/
    $len=count($files);
    for($i=min($end,$len)-1,$list=array();$i<$len&&$i>=0&&$i>=$start;$i--){
    $list[]=$files[$i];
    }
    returnjson_encode(array(
    "state"=>"SUCCESS",
    "list"=>$list,
    "start"=>$start,
    "total"=>count($files)
    ));
    }
    privatefunction_getfiles($path,$allowFiles,&$files=array()){
    if(!is_dir($path))returnnull;
    if(substr($path,strlen($path)-1)!='/')$path.='/';
    $handle=opendir($path);
    while(false!==($file=readdir($handle))){
    if($file!='.'&&$file!='..'){
    $path2=$path.$file;
    if(is_dir($path2)){
    $this->_getfiles($path2,$allowFiles,$files);
    }else{
    if(preg_match("/.(".$allowFiles.")$/i",$file)){
    $files[]=array(
    'url'=>substr($path2,strlen(UPLOAD_PATH)),
    'mtime'=>filemtime($path2)
    );
    }
    }
    }
    }
    return$files;
    }
    privatefunction_crawler(){
    $config=$this->_Config();
    $fieldName=$config['catcherFieldName'];
    $up=newLibExtendUpload();
    $source=I($fieldName);
    $result=array();
    foreach($sourceas$imgUrl){
    $item=$up->saveRemote($imgUrl);
    array_push($list,array(
    "state"=>$item["state"],
    "url"=>$item["url"],
    "size"=>$item["size"],
    "title"=>htmlspecialchars($item["title"]),
    "original"=>htmlspecialchars($item["original"]),
    "source"=>htmlspecialchars($imgUrl)
    ));
    }
    returnjson_encode($result);
    }

    }

4. 怎样用php实现上传图片到数据库

php实现上传图片保存到数据库的方法。具体分析如下:

php 上传图片,一般都使用move_uploaded_file方法保存在服务器上。但如果一个网站有多台服务器,就需要把图片发布到所有的服务器上才能正常使用(使用图片服务器的除外)
如果把图片数据保存到数据库中,多台服务器间可以实现文件共享,节省空间。

首先图片文件是二进制数据,所以需要把二进制数据保存在mysql数据库。
mysql数据库提供了BLOB类型用于存储大量数据,BLOB是一个二进制对象,能容纳不同大小的数据。

BLOB类型有以下四种,除存储的最大信息量不同外,其他都是一样的。可根据需要使用不同的类型。

TinyBlob 最大 255B
Blob 最大 65K
MediumBlob 最大 16M
LongBlob 最大 4G

数据表photo,用于保存图片数据,结构如下:

CREATETABLE`photo`(
`id`int(10)unsignedNOTNULLauto_increment,
`type`varchar(100)NOTNULL,
`binarydata`mediumblobNOTNULL,
PRIMARYKEY(`id`)
)ENGINE=MyISAMDEFAULTCHARSET=latin1AUTO_INCREMENT=1;

upload_image_todb.php代码如下:

<?php
//连接数据库
$conn=@mysql_connect("localhost","root","")ordie(mysql_error());
@mysql_select_db('demo',$conn)ordie(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="insertintophoto(type,binarydata)values('".$type."','".$image."')";
@mysql_query($sqlstr)ordie(mysql_error());
header('location:upload_image_todb.php');
exit();
//显示图片
}elseif($action=='show'){
$id=isset($_GET['id'])?intval($_GET['id']):0;
$sqlstr="select*fromphotowhereid=$id";
$query=mysql_query($sqlstr)ordie(mysql_error());
$thread=mysql_fetch_assoc($query);
if($thread){
header('content-type:'.$thread['type']);
echo$thread['binarydata'];
exit();
}
}else{
//显示图片列表及上传表单
?>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="content-type"content="text/html;charset=utf-8">
<title>uploadimagetodbdemo</title>
</head>

<body>
<formname="form1"method="post"action="upload_image_todb.php"enctype="multipart/form-data">
<p>图片:<inputtype="file"name="photo"></p>
<p><inputtype="hidden"name="action"value="add"><inputtype="submit"name="b1"value="提交"></p>
</form>

<?php
$sqlstr="select*fromphotoorderbyiddesc";
$query=mysql_query($sqlstr)ordie(mysql_error());
$result=array();
while($thread=mysql_fetch_assoc($query)){
$result[]=$thread;
}
foreach($resultas$val){
echo'<p><img
src="upload_image_todb.php?action=show&id='.$val['id'].'&t='.time().'"
width="150"></p>';
}
?>
</body>
</html>
<?php
}
?>

程序运行截图和数据库截图:

5. PHP上传多张图片代码

<?php } function news(){?>
<form action="?type=proctNews" method="post" enctype="multipart/form-data" name="form1" id="form1">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr><td> </td></tr><tr><td height="30"><label>名称A:
<input name="title" type="text" id="title" size="30" />
</label></td></tr><tr><td height="30"><label>名称B:
<input name="title_en" type="text" id="title_en" size="30" />
</label></td></tr><tr><td height="30"><label>分类:
<select name="ptype" id="ptype">
<?php $conn = new db_conn();
$sql = "SELECT * FROM proct_type";
$result = $conn->db_query($sql);
while($rows=mysql_fetch_assoc($result)){?>
<option value="<?php echo $rows['id']; ?>"><?php echo $rows['name']." / ".$rows['name_en']; ?></option>
<?php } $conn->db_close(); ?>
</select>
</label></td></tr><tr><td height="30"><label>图片:<br>
<input name="file[]" type="file" size="50" /><br>
<input name="file[]" type="file" size="50" /><br>
<input name="file[]" type="file" size="50" /><br>
<input name="file[]" type="file" size="50" /><br>
<input name="file[]" type="file" size="50" /><br>
<input name="file[]" type="file" size="50" /><br>
</label></td></tr><tr><td>说明A:
<input name="text" type="text" id="text" size="30" /></td>
</tr><tr><td>说明B:
<input name="en_text" type="text" id="en_text" size="30" /></td>
</tr><tr><td align="center"><label>
<input type="submit" name="button" id="button" value="提交" />
</label></td></tr><tr><td> </td></tr></table></form>
<?php }function proctNews(){
extract($_POST);
$upimage = "upimage/".date("Ym")."/";//上传位置
if(!is_dir($upimage)){
mkdir($upimage); }

$filenum=count($_FILES['file']['tmp_name']);
for($i=0;$i<$filenum;$i++){

$file = "";
if(is_uploaded_file($_FILES['file']['tmp_name'][$i])){//是否用POST上传
if($_FILES['file']['type'][$i] != ("image/jpeg" || "image/pjpeg")){
die(printTop("只能上传jpg图像!")); }
$im = imagecreatefromjpeg($_FILES['file']['tmp_name'][$i]);
$file = $upimage.date("YmdHis").rand(1000,9999);
$w = imagesx($im);
$h = imagesy($im);
if($w > 800 || $h > 800){
ResizeImage($im,800,800,$file.".jpg");
}else{ move_uploaded_file($_FILES['file']['tmp_name'][$i],$file.".jpg");}

//以下为增加行
//设置水印类型 1字符串 2图片 请自行设置
$watertype=1;
//设置水印字符串 请自行设置
$waterstring="MY hand MY mouth";
//设置水印图片名 请自行设置
$waterimage="water.gif";
$destination=$file.".jpg";
$image_size = getimagesize($destination);

$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);

$simage =imagecreatefromjpeg($destination);
image($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);
imagefilledrectangle($nimage,1,$image_size[1]-15,120,$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");
image($nimage,$simage1,0,0,0,0,85,15);
imagedestroy($simage1);
break;
}
imagejpeg($nimage, $destination);
imagedestroy($nimage);
imagedestroy($simage);
//以上为增加行//

ResizeImage($im,130,130,$file."n.jpg");}
$date = date("Y-m-d H:i:s");
$conn = new db_conn();
$sql = "INSERT INTO proct (ptype,title,title_en,image,text,text_en,date) VALUES ($ptype,'$title','$title_en','$file','$text','$text_en','$date')";
$result = $conn->db_query($sql);
if($result){
echo printTop("添加成功!");}else{
echo printTop("添加失败!");}
$conn->db_close();}
}
function types(){?>

6. PHP怎样上传图片以及预览图片

本地图片,就搞个img,设置他的src就可以实现;
参考如下:

<div class="column " style="width: 400px; margin-left: 200px;" id="imageShow">
<div id="proctImageNew">@*用于图片预览*@
</div>
<div id="proctImage">
<div class="widget the-common-margin-top" style="height: 400px; border: 1px solid #eeeeee;
padding: 3px;">
<img id="imgHolder" style="max-height: 390px; max-width: 390px;" />
</div>
</div>
</div>
<form id="formImageUpload" name="formImageUpload" method="post" action="/DocTeam/ProctsImage/UploadImage"
enctype="multipart/form-data">
<div id="fileDiv">
<input type="file" id="theFile" name="theFile" size="20" style="cursor: pointer;
width: 65px; height: 60px; position: absolute; filter: alpha(opacity:1); -moz-opacity: 0;
opacity: 0; z-index: 102;" />
</div>
<input type="hidden" name="imageId_hide" id="imageId_hide" />
</form>
<div id="cover" style="position: absolute; background-color: White; z-index: 10;
filter: alpha(opacity=100); -moz-opacity: 1; opacity: 1; overflow: auto; width: 400px;">
<input id="selectImage" type="button" style="width: 65px; height: 60px;" value="Select" />
<br />
<br />
<input type="button" value="Upload" id="imageUpload" style="width: 65px; height: 60px;"
disabled="disabled" onclick="javascript:uploadImage();" />
</div>

//js本地图片预览,兼容ie[6-9]、火狐、Chrome17+、Opera11+、Maxthon3
function PreviewImage(fileObj, imgPreviewId, divPreviewId) {
var allowExtention = ".jpg,.bmp,.gif,.png"; //允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value;
var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
var browserVersion = window.navigator.userAgent.toUpperCase();
if (allowExtention.indexOf(extention) > -1) {
if (fileObj.files) {//HTML5实现预览,兼容chrome、火狐7+等
if (window.FileReader) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
}
reader.readAsDataURL(fileObj.files[0]);
} else if (browserVersion.indexOf("SAFARI") > -1) {
alert("不支持Safari6.0以下浏览器的图片预览!");
}
} else if (browserVersion.indexOf("MSIE") > -1) {
if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
} else {//ie[7-9]
fileObj.select();
if (browserVersion.indexOf("MSIE 9") > -1)
fileObj.blur(); //不加上document.selection.createRange().text在ie9会拒绝访问
var newPreview = document.getElementById(divPreviewId + "New");
if (newPreview == null) {
newPreview = document.createElement("div");
newPreview.setAttribute("id", divPreviewId + "New");
}
var a = document.selection.createRange().text;
// newPreview.style.width = document.getElementById(imgPreviewId).width + "px";
// newPreview.style.height = document.getElementById(imgPreviewId).height + "px";
//newPreview.style.width = 390 + "px";
newPreview.style.height = 390 + "px";
newPreview.style.border = "solid 1px #eeeeee";
newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
var tempDivPreview = document.getElementById(divPreviewId);
// tempDivPreview.parentNode.insertBefore(newPreview, tempDivPreview);
newPreview.style.display = "block";
tempDivPreview.style.display = "none";

}
} else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);
if (firefoxVersion < 7) {//firefox7以下版本
document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
} else {//firefox7.0+
document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
}
} else {
document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
}
} else {
alert("仅支持" + allowExtention + "为后缀名的文件!");
fileObj.value = ""; //清空选中文件
if (browserVersion.indexOf("MSIE") > -1) {
fileObj.select();
document.selection.clear();
}
fileObj.outerHTML = fileObj.outerHTML;
}
}

function setTheFileButton_Cover_SelectImageButton() {
// debugger;
// var position = $("#selectImage", "#cover").position();
// var css = { top: position.top, left: position.left };
// $("#theFile", "#fileDiv").css(css);
}

var $imgHolder = $('#imgHolder', "#proctImage");
var tempDiv = $("#temp_div");
$("#select", "#cover").click(function () {
$("#theFile", "#fileDiv").click().select();
});
$("#theFile", "#fileDiv").click(function () {
$(this).blur();
});
$("#theFile", "#fileDiv").change(function () {
PreviewImage(this, 'imgHolder', 'proctImage');
setTheFileButton_Cover_SelectImageButton();
// alert("预览已生成!");
$("#imageUpload").prop("disabled", false);
});

7. 如何在php上实现文件上传功能

PHP 一般使用 POST 方法上传文件,下面是一个简单的文件上传示例,里面有相关的注释:
up.htm 文件:
----------
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Up Sample</title>
</head>
<body>
<form action="up.php" method="post" enctype="multipart/form-data">
<!--备注:表单中 enctype="multipart/form-data " 的意思,是设置表单的 MIME 编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了 multipart/form-data ,才能完整的传递文件数据,进行下面的操作,并且 method 要设置为 "post"-->
File:<br />
<input type="file" name="upfile" size="30"><br />

<!--上传框要设置 type="file"-->

<br />
<input type="submit" value="Upload">
</form>
</body>
</html>
----------
up.php 文件
----------
<?php
if (is_uploaded_file($_FILES["upfile"]["tmp_name"])){

//如果有文件上传
//is_uploaded_file -- 判断文件是否是通过 HTTP POST 上传的,返回布尔值
//$_FILES['upfilename']['...'],其中的 'upfilename' 即为上传框的 name 属性
//$_FILES['upfile']['tmp_name'] -- 文件被上传后在服务端储存的临时文件名,一般是系统默认
if(!eregi('pdf', $_FILES['upfile']['type'])){

//我们这里假设你要上传一个 pdf 文件
//if(!eregi('pdf', $_FILES['upfile']['type'])) 这个是判断上传文件类型的,是不是 pdf 文件,当然,若是想判断是否是 jpg 文件的话,将 pdf 改成 jpg 就可以了,即 if(!eregi('jpg', $_FILES['upfile']['type']))
//$_FILES['upfile']['type'] 是文件的 MIME 类型,如果浏览器提供此信息的话。例如“image/gif”
echo 'The uploaded file is not an pdf File! Please upload a right file!';
}else{
$filename = $_FILES['upfile']['name'];
//$filename = $_FILES['upfile']['name'],这里是指定上传后的文件名,这里使用的仍是原来的文件名字,($_FILES['upfile']['name'] 是原始文件的名字)
if(move_uploaded_file($_FILES["upfile"]["tmp_name"], dirname(__FILE__)."/upload_file/".$filename)){

//这里就是上传文件
//dirname(__FILE__)."/upload_file/".$file_name -- 指定上传的目标文件,假设你要上传的目标文件夹upload_file 是和当前文件(upload.php)在同一文件夹下
//chmod(dirname(__FILE__)."/upload_file/". $file_name, 0444);
//上面注释掉的是用来改变上传后文件的属性,444 即只有执行和读的权限(看情况加上)
echo $_FILES["upfile"]["name"] . " uploaded succeed!!!";

}else{
echo "Can't upload!!!";
}
}
}else{
echo "File is not selected";
}
//需要注意的:
/*
在你的 up.php 同级目录下建立 upload_file 文件夹,来存放上传的文件
在上传之前要看一下 php 的配置文件:php.ini 中的三处设置
1.是否允许文件上传:( file_uploads = On )
2.文件上传的最大 size:( upload_max_filesize )
3.post 的最大 size ( post_max_size ) 这个大小设置成和 uplod_max_filesize 一样大或比 uplod_max_filesize 大
*/
/*
这只是很简单的一个文件上传的例子,为了帮助理解,只是判断了一下上传文件的类型,还可以使用 if 语句来判断上传文件的大小($_FILES['upfile']['type'])),并进行提示控制等,相关可以查阅 $_FILE['upfile'] 数组的各个值分别代表什么
*/
?>

8. 用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>
<title>M4U 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>
<center><form enctype="multipart/form-data" method="post" name="upform">
上传文件: <br><br><br>
<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"><br><br><br>
允许上传的文件类型为:jpg|jpeg|png|pjpeg|gif|bmp|x-png|swf <br><br>
<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>已经成功上传</font><br>文件名: <font color=blue>".$destination_folder.$fname."</font><br>";
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;
}

image($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");
image($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>

9. php上传图片的问题!

首先在php的目录下,建一个images的文件夹

把以代码另存为upload.php
<form name="newad" method="post" enctype="multipart/form-data" action="">
<table>
<tr><td><input type="file" name="image" ></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
</table>
</form>PHP Code
<?php
//define a maxim size for the uploaded images
define ("MAX_SIZE","10000000");
// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","170");
define ("HEIGHT","120");

// this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and height defined, but without deforming the image
function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);

if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);

//gets the dimmensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);

// next we will calculate the new dimmensions for the thumbnail image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimmensions with the new ones
// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
// and the height will be calculated so the image ratio will not change
// 3. otherwise we will use the height ratio for the image
// as a result, only one of the dimmensions will be from the fixed ones
$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if($ratio1>$ratio2) {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}

// we create a new image with the new dimmensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

// resize the big image to the new created one
imageresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_img,$filename);
else
imagejpeg($dst_img,$filename);

//destroys source and destination images.
imagedestroy($dst_img);
imagedestroy($src_img);
}

// This function reads the extension of the file.
// It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

// This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.
$errors=0;
// checks if the form has been submitted
if(isset($_POST['Submit']))
{
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
// if it is not empty
if ($image)
{
// get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);

// get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
// if it is not a known extension, we will suppose it is an error, print an error message
//and will not upload the file, otherwise we continue
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png"))
{
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
// get the size of the image in bytes
// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=getimagesize($_FILES['image']['tmp_name']);
$sizekb=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}

//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="images/".$image_name;
$copied = ($_FILES['image']['tmp_name'], $newname);
//we verify if the image has been uploaded, and print error instead
if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}
else
{
// the new thumbnail image will be placed in images/thumbs/ folder
$thumb_name='images/'.$image_name;
// call the function that will create the thumbnail. The function will get as parameters
//the image name, the thumbnail name and the width and height desired for the thumbnail
$thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
}} }}
//If no errors registred, print the success message and show the thumbnail image created
if(isset($_POST['Submit']) && !$errors)
{
echo "<h1>Thumbnail created Successfully!</h1>";
echo '<img src="'.$thumb_name.'">';
}
?>

10. 跪求PHP上传图片并按比例缩放到一定尺寸的程序,非常感谢

publicfunctionupimges(){
$filename=time();
header("Content-Type:text/html;charset=utf-8");
$upload=newUpimage('','','','',$filename);
//设置上传文件大小
$upload->maxSize=100000000000000;
//$upload->saveRule=microtime().'_'.mt_rand(1000,9999);
//上传文件命名规则timeuniqidcom_create_guid等
//$upload->$saveRule=time();
//设置上传文件类型
$upload->allowExts=explode(',','jpg,gif,png,jpeg');
//设置附件上传目录
$upload->savePath='./data/attached/skp/'.$_SESSION['formtoken'].'/';
$upload->thumb=true;
//设置引用图片类库包路径
$upload->imageClassPath='./Image.php';
//设置需要生成缩略图的文件后缀
$upload->thumbPrefix='thumb_,thumbm_,thumbl_,thumbs_';//生产4张缩略图
//设置缩略图最大宽度
$upload->thumbMaxWidth='960,480,120,64';
//设置缩略图最大高度
$upload->thumbMaxHeight='960,480,120,64';
//删除原图
$upload->thumbRemoveOrigin=false;

if(!$upload->upload()){
$data['tip']=$upload->getErrorMsg();
$data['status']='0';
}else{
$info=$upload->getUploadFileInfo();

$data['counts']=count($info);
$data['status']='1';
$data['tip']='上传成功';
$data['info']=$info;
}

echojson_encode($data);
}

这个是代码和所引用的

阅读全文

与phpuploadimage相关的资料

热点内容
数据库查询系统源码 浏览:617
php5314 浏览:357
完美国际安装到哪个文件夹 浏览:668
什么app可以扫一扫做题 浏览:539
程序员编码论坛 浏览:923
淘点是什么app 浏览:659
中国高等植物pdf 浏览:453
51单片机时间 浏览:182
后台如何获取服务器ip 浏览:267
单片机流水灯程序c语言 浏览:234
程序员第二职业挣钱 浏览:238
运行里怎么输入服务器路径 浏览:840
pythonstepwise 浏览:509
刘一男词汇速记指南pdf 浏览:64
php认证级别 浏览:368
方舟编译啥时候推送 浏览:1011
php手机验证码生成 浏览:675
哲学思维pdf 浏览:14
凌达压缩机有限公司招聘 浏览:534
weblogic命令部署 浏览:37