導航:首頁 > 編程語言 > 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相關的資料

熱點內容
設計道pdf 瀏覽:615
單片機kill4軟體下載收費嗎 瀏覽:846
蘋果手機怎麼連接RMS伺服器 瀏覽:603
cisco路由器基本配置命令 瀏覽:186
android狀態欄顏色透明 瀏覽:116
db2編譯工具 瀏覽:181
騰訊雲伺服器創建環境 瀏覽:567
監管資金怎麼解壓 瀏覽:671
榮耀手機內存清理文件夾 瀏覽:175
外派程序員方案 瀏覽:554
安卓怎麼把桌面的軟體變成卡通 瀏覽:885
魯班鎖解壓嗎 瀏覽:395
打包發送文件如何加密 瀏覽:213
centos解壓縮zip 瀏覽:388
我的世界怎麼用命令風塊取消指令 瀏覽:1000
安卓軟體請求超時怎麼辦 瀏覽:476
androidapp調用另一個app 瀏覽:621
數控銑床法蘭克子程序編程 瀏覽:174
linux打包命令targz 瀏覽:997
抖音app是哪個 瀏覽:407