A. PHP如何实现表单提交时用户上传头像到数据
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>注册页面</title>
</head>
<body>
<form action="enteringDb.php" method="post" enctype="multipart/form-data">
<table border="1">
<tr><th colspan="2">注册页面</th></tr>
<tr><td>用户名</td><td><input type="text" name="name" size="30" maxlength="10"/></td></tr>
<tr><td>请上传用户头像</td><td><input type="file" name="file" id="file"/></td></tr>
<tr><td>
<input type="submit" name="submit" value="提交"/>
<input type="reset" value="重置"/>
</td></tr>
</table>
</form>
</body>
</html>
B. 求php文件上传源码
<?php
//文件和图片上传类
class UploadFile
{//类定义开始
public $maxSize = -1; // 上传文件的最大值
public $supportMulti = true; // 是否支持多文件上传
public $allowExts = array();// 允许上传的文件后缀// 留空不作后缀检 查
public $allowTypes = array(); // 允许上传的文件类型 // 留空不做检查
public $thumb = false; // 使用对上传图片进行缩略图处理
public $thumbMaxWidth; // 缩略图最大宽度
public $thumbMaxHeight; // 缩略图最大高度
public $thumbPrefix = 'thumb_'; // 缩略图前缀
public $thumbSuffix = '';
public $thumbPath = ''; // 缩略图保存路径
public $thumbFile = '';// 缩略图文件名
public $thumbRemoveOrigin =false;// 是否移除原图
public $zipImages = false; // 压缩图片文件上传
public $autoSub = false; // 启用子目录保存文件
public $subType = 'hash';// 子目录创建方式 可以使用hash date
public $dateFormat = 'Ymd';
public $hashLevel = 1; // hash的目录层次
public $savePath = ''; // 上传文件保存路径
public $autoCheck = true; // 是否自动检查附件
public $uploadReplace = false;// 存在同名是否覆盖
// 例如可以是 time uniqid com_create_guid 等
// 必须是一个无需任何参数的函数名 可以使用自定义函数
public $saveRule = '';// 上传文件命名规则
// 例如可以是 md5_file sha1_file 等// 上传文件Hash规则函数名
public $hashType = 'md5_file';
private $error = '';// 错误信息
private $uploadFileInfo ;// 上传成功的文件信息
/**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($maxSize='',$allowExts='',$allowTypes='',$savePath='',$saveRule='')
{
if(!empty($maxSize) && is_numeric($maxSize)) {
$this->maxSize = $maxSize;
}
if(!empty($allowExts)) {
if(is_array($allowExts)) {
$this->allowExts = array_map('strtolower',$allowExts);
}else {
$this->allowExts = explode(',',strtolower($allowExts));
}
}
if(!empty($allowTypes)) {
if(is_array($allowTypes)) {
$this->allowTypes = array_map('strtolower',$allowTypes);
}else {
$this->allowTypes = explode(',',strtolower($allowTypes));
}
}
if(!empty($savePath)) {
$this->savePath = $savePath;
}
if(!empty($saveRule)) {
$this->saveRule = $saveRule;
}
}
private function save($file)
{
$filename = $file['savepath'].$file['savename'];
if(!$this->uploadReplace && is_file($filename)) {// 不覆盖同名文件
$this->error = '文件已经存在!'.$filename;
return $this -> error;
}
// 如果是图像文件 检测文件格式
if( in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png','swf')) && $this -> error === getimagesize($file['tmp_name'])) {
$this->error = '非法图像文件';
return $this -> error;
}
if(!move_uploaded_file($file['tmp_name'], iconv('utf-8','gbk',$filename))) {
$this->error = '文件上传保存错误!';
return $this -> error;
}
if($this->thumb && in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png'))) {
$image = getimagesize($filename);
if($this -> error !== $image) {
//是图像文件生成缩略图
$thumbWidth = explode(',',$this->thumbMaxWidth);
$thumbHeight = explode(',',$this->thumbMaxHeight);
$thumbPrefix = explode(',',$this->thumbPrefix);
$thumbSuffix = explode(',',$this->thumbSuffix);
$thumbFile = explode(',',$this->thumbFile);
$thumbPath =
$this->thumbPath?$this->thumbPath:$file['savepath'];
// 生成图像缩略图
if(file_exists(dirname(__FILE__).'/Image.class.php'))
{
require_once(dirname(__FILE__).'/Image.class.php');
$realFilename = $this->autoSub?basename($file['savename']):$file['savename'];
for($i=0,$len=count($thumbWidth); $i<$len; $i++) {
$thumbname = $thumbPath.$thumbPrefix[$i].substr($realFilename,0,strrpos($realFilename, '.')).$thumbSuffix[$i].'.'.$file['extension'];
Image::thumb($filename,$thumbname,'',$thumbWidth[$i],$thumbHeight[$i],true);
}
if($this->thumbRemoveOrigin) {
// 生成缩略图之后删除原图
unlink($filename);
}
}
}
}
return true;
}
/**
+----------------------------------------------------------
* 上传文件
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $savePath 上传文件保存路径
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function upload($savePath ='') {
if(empty($savePath)) //如果不指定保存文件名,则由系统默认
$savePath = $this->savePath;
$savePath .= date('Ym',time())."/";
if(!is_dir($savePath)) { // 检查上传目录
if(is_dir(base64_decode($savePath))) {// 检查目录是否编码后的
$savePath = base64_decode($savePath);
}else{
if(!mkdir($savePath)){ // 尝试创建目录
$this->error = '上传目录'.$savePath.'不存在';return $this -> error;
}
}
}else {
if(!is_writeable($savePath)) {
$this->error = '上传目录'.$savePath.'不可写'; return $this -> error;
}
}
$fileInfo = array();
$isUpload = $this -> error;
// 获取上传的文件信息
// 对$_FILES数组信息处理
$files = $this->dealFiles($_FILES);
foreach($files as $key => $file) {
//过滤无效的上传
if(!empty($file['name'])) {
//登记上传文件的扩展信息
$file['key'] = $key;
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);
// 自动检查附件
if($this->autoCheck) {
if(!$this->check($file))
return $this -> error;
}
//保存上传文件
//echo "<pre>";print_r( $file );
if(!$this->save($file)) return $this -> error;
/*
if(function_exists($this->hashType)) {
$fun = $this->hashType;
$file['hash'] = $fun(auto_charset($file['savepath'].$file['savename'],'utf-8','gbk'));
}
*/
//上传成功后保存文件信息,供其他地方调用
unset($file['tmp_name'],$file['error']);
$fileInfo[] = $file;
$isUpload = true;
}
}
if($isUpload) {
$this->uploadFileInfo = $fileInfo;
return $fileInfo;
}else {
$this->error = '没有选择上传文件';
return $this -> error;
}
}
/**
+----------------------------------------------------------
* 转换上传文件数组变量为正确的方式
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $files 上传的文件变量
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
private function dealFiles($files) {
$fileArray = array();
foreach ($files as $file){
if(is_array($file['name'])) {
$keys = array_keys($file);
$count = count($file['name']);
for ($i=0; $i<$count; $i++) {
foreach ($keys as $key)
$fileArray[$i][$key] = $file[$key][$i];
}
}else{
$fileArray = $files;
}
break;
}
return $fileArray;
}
/**
+----------------------------------------------------------
* 获取错误代码信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $errorNo 错误号码
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
protected function error($errorNo)
{
switch($errorNo) {
case 1:
$this->error = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
break;
case 2:
$this->error = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
break;
case 3:
$this->error = '文件只有部分被上传';
break;
case 4:
$this->error = '没有文件被上传';
break;
case 6:
$this->error = '找不到临时文件夹';
break;
case 7:
$this->error = '文件写入失败';
break;
default:
$this->error = '未知上传错误!';
}
return ;
}
/**
+----------------------------------------------------------
* 根据上传文件命名规则取得保存文件名
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 数据
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function getSaveName($filename)
{
$rule = $this->saveRule;
if(empty($rule)) {//没有定义命名规则,则保持文件名不变
$saveName = $filename['name'];
}else {
if(function_exists($rule)) {
//使用函数生成一个唯一文件标识号
$saveName = $rule().rand(1001,9999).".".$filename['extension'];
}else {
//使用给定的文件名作为标识号
$saveName = $rule.rand(1001,9999).".".$filename['extension'];
}
}
if($this->autoSub) {
// 使用子目录保存文件
$saveName = $this->getSubName($filename).'/'.$saveName;
}
return $saveName;
}
/**
+----------------------------------------------------------
* 获取子目录的名称
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $file 上传的文件信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function getSubName($file)
{
switch($this->subType) {
case 'date':
$dir = date($this->dateFormat,time());
break;
case 'hash':
default:
$name = md5($file['savename']);
$dir = '';
for($i=0;$i<$this->hashLevel;$i++) {
$dir .= $name{0}.'/';
}
break;
}
if(!is_dir($file['savepath'].$dir)) {
mkdir($file['savepath'].$dir);
}
return $dir;
}
/**
+----------------------------------------------------------
* 检查上传的文件
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $file 文件信息
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function check($file) {
if($file['error']!== 0) {
//文件上传失败
//捕获错误代码
$this->error($file['error']);
return $this -> error;
}
//检查文件Mime类型
if(!$this->checkType($file['type'])) {
$this->error = '上传文件MIME类型不允许!';
return $this -> error;
}
//检查文件类型
if(!$this->checkExt($file['extension'])) {
$this->error ='上传文件类型不允许';
return $this -> error;
}
//文件上传成功,进行自定义规则检查
//检查文件大小
if(!$this->checkSize($file['size'])) {
$this->error = '上传文件大小超出限制!';
return $this -> error;
}
//检查是否合法上传
if(!$this->checkUpload($file['tmp_name'])) {
$this->error = '非法上传文件!';
return $this -> error;
}
return true;
}
/**
+----------------------------------------------------------
* 检查上传的文件类型是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $type 数据
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkType($type)
{
if(!empty($this->allowTypes))
return in_array(strtolower($type),$this->allowTypes);
return true;
}
/**
+----------------------------------------------------------
* 检查上传的文件后缀是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $ext 后缀名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkExt($ext)
{
if(!empty($this->allowExts))
return in_array(strtolower($ext),$this->allowExts,true);
return true;
}
/**
+----------------------------------------------------------
* 检查文件大小是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param integer $size 数据
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkSize($size)
{
return !($size > $this->maxSize) || (-1 == $this->maxSize);
}
/**
+----------------------------------------------------------
* 检查文件是否非法提交
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 文件名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkUpload($filename)
{
return is_uploaded_file($filename);
}
/**
+----------------------------------------------------------
* 取得上传文件的后缀
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 文件名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function getExt($filename)
{
$pathinfo = pathinfo($filename);
return $pathinfo['extension'];
}
/**
+----------------------------------------------------------
* 取得上传文件的信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getUploadFileInfo()
{
return $this->uploadFileInfo;
}
/**
+----------------------------------------------------------
* 取得最后一次错误信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getErrorMsg()
{
return $this->error;
}
}//类定义结束
?>
C. 用PHP怎么上传web用户头像呢😢
index.php:
<?php
echo"
<form action='uploadfile.php' method='post' enctype='multipart/formdata'>
<input type='file' name='file'>
<input type='submit' value='上传'>
</form>
";
?>
uploadfile.php:
<?php
//接受图片
$file=$_FILES['file'];
// echo '<pre>';
// print_r($file);
$parr=explode('.',$file['name']);
$hz=$parr[count($parr)-1];
$newfilename=date('YmdHis',time()).rand(1000,9999).'.'.$hz;
if(move_uploaded_file($file['tmp_name'],'./img/'.$newfilename))
{
$headimgurl='http://yourIP/img/'.$newfilename;
}
?>
D. php怎么实现头像上传到客户端
php根据APP的上传方式来决定PHP端的获取方式,多数都是表单式上传。
$_FILES; file_get_contents('php://input')都可以。
还有的是先在客户端读取了文件内容,再base64编码,再上传。
比较简单的大文件断点上传,其实就可以靠APP处理。
E. 用PHP上传用户头像怎么解😢
修改第一
echo " <tr><form action = 'info.php?id=$row[imgid]' method = 'post'> ";
修改第二:
你在info.php中接受你传过来的id
加入用$cls = $_POST["id"];
然后把id在这样传值
echo "<img src='image.php?imgid=$cls'>";
最后
$img_sql="select image_id,content from nsms_images where image_id='$imgid'";这里就可以得到参数了
F. php上传用户头像功能,请问我这样做对吗就是直接把用户上传的原始大小的头像图片显示在页面上,在设
不好,如果客户上传的图标有3M大小,设置成头像的话,加载就需要半天,一半是利用php生成缩略图。将缩略图设置为头像
G. php怎么上传头像
php上传头像的功能需要掌握的就是有关文件上传类的php知识,需要知道的图片的格式,图片上传大小的限制,需要用到的函数有is_uploaded_file(文件上传的方式)等等,这里举个例子:
$allowType = array('image/png', 'image/jpeg', 'image/gif');
//做上传图片的验证
//使用try/catch来做判断
try{
if ( !is_uploaded_file($_FILES['thumb']['tmp_name']) ) {
throw new Exception('缩略图上传错误'); //抛出错误
}
if ( !is_uploaded_file($_FILES['img']['tmp_name']) ) {
throw new Exception('大图上传错误'); //抛出错误
}
if ( !in_array($_FILES['thumb']['type'], $allowType) ) {
throw new Exception('缩略图格式错误'); //抛出错误
}
if ( !in_array($_FILES['img']['type'], $allowType) ) {
throw new Exception('大图格式错误'); //抛出错误
}
if ( !($_FILES['thumb']['size'] <= 2*1024*1024) ) {
throw new Exception('缩略图大小错误'); //抛出错误
}
if ( !($_FILES['img']['size'] <= 2*1024*1024) ) {
throw new Exception('大图大小错误'); //抛出错误
}
$thumb_filename = time().mt_rand().substr($_FILES['thumb']['name'], strrpos($_FILES['thumb']['name'], '.'));
$img_filename = mt_rand().time().substr($_FILES['img']['name'], strrpos($_FILES['img']['name'], '.'));
if ( !move_uploaded_file($_FILES['thumb']['tmp_name'], UPLOAD_PATH.'/goods/'.$thumb_filename) ) {
throw new Exception('缩略图上传失败'); //抛出错误
}
if ( !move_uploaded_file($_FILES['img']['tmp_name'], UPLOAD_PATH.'/goods/'.$img_filename) ) {
throw new Exception('大图上传失败'); //抛出错误
}
} catch ( Exception $e ) {
$message = $e->getMessage();
}
这个函数实现了对图片的类型的判断,大小的判断,还有上传图片的命名。
H. 用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>
I. php上传文件如何实现上传头像的时候可以显示出头像
两种方案:
前端直接使用 FileReader可以直接读取图片在前端显示,可以在用户点击确定后再通过 ajax上传到后端(当然,你也可以直接通过 form表单 submit提交)
用户点击上传文件的时候,直接用 ajax把图片是传到后端,后端回传图片在服务器中的地址,前端把这个图片显示出来。
J. 如何用thinkPHP实现 类似于QQ头像上传的功能
1.建立图片上传通道
2.传成功后把返回的路径保存在该用户的表中