实例演示图片上传
思路:
1.通过HTML的文件域建立上传表单,注意
enctype属性,必须等于"multipart/form-data"
2.使用javasrcipt实现文件预览 事实上就是判断文件是否为指定格式,然后把上传内容给id为syt的元素
<scriptlanguage="javascript"> functionyulan() { varfileext=document.myform.pic.value.substring(document.myform.pic.value.lastIndexOf("."),document.myform.pic.value.length) fileext=fileext.toLowerCase() if((fileext!='.jpg')&&(fileext!='.gif')&&(fileext!='.jpeg')&&(fileext!='.png')&&(fileext!='.bmp')) { alert('对不起,系统只支持指定格式的文件,请调整后重新上传') document.myform.pic.focus; } else{ document.getElementById("syt").innerHTML="<imgsrc='"+document.myform.pic.value+"'width='150px'>"; } } </script>
然后通过$_FILES函数,获得临时文件名,文件类型,文件尺寸,文件名等信息
用 is_uploaded_file 函数判断,用户是否上传了图片,然后用mkdir创建文件夹,
使用$newfile=date('YmdHis'); $filename=$dir."/".$newfile.$ext; 自定义上传的文件名
最后,用move_uploaded_file函数来实现把文件从临时区移动到指定的文件夹
<? header('Content-Type:text/html;charset=utf-8'); include('function.php'); $error=$_FILES['pic']['error']; $name=$_FILES['pic']['name']; $tmp_name=$_FILES['pic']['tmp_name']; $type=$_FILES['pic']['type']; $size=$_FILES['pic']['size']; if($name<>"") { $ext=substr($name,-4); if($ext!='.jpg'&&$ext!='.bmp'&&$ext!='.gif'&&$ext!='.png'&&$ext!='jpeg') { echo"<scriptlanguage='javascript'>alert('您选择的图片格式不正确');history.go(-1);</script>"; } else{ if(is_uploaded_file($tmp_name)) { $dir=date('Y-m-d'); mk($dir); $newfile=date('YmdHis'); $filename=$dir."/".$newfile.$ext; if(!move_uploaded_file($tmp_name,$filename)) { echo"<scriptlanguage='javascript'>alert('对不起,文件移动失败');history.go(-1);</script>"; exit(); } else{ echo"<scriptlanguage='javascript'>alert('文件上传成功');location.href='upfile.php';</script>"; } } } } else{ echo"<scriptlanguage='javascript'>alert('请选择文件');history.go(-1);</script>"; } ?>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。