php Ajax 文件上传实例分析
如何实现异步文件上传
有了file filereader 对象的支持,异步文件上传将变得简单。(以前都会把form提交到iframe来实现)
1:取得file对象
2:读取2进制数据
3:模拟http请求,把数据发送出去(这里通常比较麻烦)
在forefox下使用 xmlhttprequest 对象的 sendasbinary 方法发送数据;
4:完美实现
遇到的问题
目前仅有 firefox 可以正确上传文件。(chrome也可以采google.gears上传)
对于从firefox和chrome下读取到的文件数据好像不一样(不知道是否是调试工具的原因)
chrome以及其他高级浏览器没有 sendasbinary 方法 只能使用 send 方法发送数据,有可能是上面的原因导致无法正确上传。(经过测试普通文本文件可以正确上传)
<!doctype html >
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>html5 file and filereader</title>
<link href="html/ui.css教程" _mce_href="html/ui.css" rel="stylesheet" />
</head>
<body>
<style type="text/css"><!--
.box{background:#f8f8f8;border:1px solid #ccc;padding:10px;-webkit-box-shadow:#000 0px 0px 4px;-moz-box-shadow:#000 0px 0px 4px;
-webkit-border-radius:2px;font-family: 'segoe ui', calibri, 'myriad pro', myriad, 'trebuchet ms', helvetica, arial, sans-serif;
}
.bl{ font-weight:700;}
.dl{ padding:10px; border-top:1px dotted #999;}
.dl dd{ padding:0; margin:0;}
.log{border:1px solid #ccc; background:#f8f8f8; width:200px; position:absolute; right:10px; top:10px;}
.log li{border:1p dotted #ccc;word-wrap:break-word;word-break:break-all; margin:0px; padding:0;}
.log ul{margin:0px; padding:0; list-style:none;}
--></style><style type="text/css" _mce_bogus="1"><!--
.box{background:#f8f8f8;border:1px solid #ccc;padding:10px;-webkit-box-shadow:#000 0px 0px 4px;-moz-box-shadow:#000 0px 0px 4px;
-webkit-border-radius:2px;font-family: 'segoe ui', calibri, 'myriad pro', myriad, 'trebuchet ms', helvetica, arial, sans-serif;
}
.bl{ font-weight:700;}
.dl{ padding:10px; border-top:1px dotted #999;}
.dl dd{ padding:0; margin:0;}
.log{border:1px solid #ccc; background:#f8f8f8; width:200px; position:absolute; right:10px; top:10px;}
.log li{border:1p dotted #ccc;word-wrap:break-word;word-break:break-all; margin:0px; padding:0;}
.log ul{margin:0px; padding:0; list-style:none;}
--></style>
<div class="box" id="baseinfo">
<h2>(把图片拖拽到这里)利用 filereader 获取文件 base64 编码</h2>
<div></div>
</div>
<div class="log">
<ul id="log">
</ul>
</div>
<script type="text/网页特效" ><!--
(function(){
window.datavalue = 0;
var html = ' <dl class="dl">
<dd>filename: $filename$</dd>
<dd>filetype: $filetype$</dd>
<dd>filesize: $filesize$</dd>
<dd><img src="$data$" /></dd>
<dd>filebase64: <br/>
<div style="width:100%; height:100px;">$filebase64$</div>
</dd>
</dl>
'
var log = function(msg){
//console['log'](msg);
document.getelementbyid('log').innerhtml += '<li>'+ msg +'</li>';
}var dp = function(){
var defconfig = {
dropwrap : window
}
this.init.apply(this, [defconfig]);
this.file = null;
}
dp.prototype = {
init:function(args){
var dropwrap = args.dropwrap;
var _this = this;
dropwrap.addeventlistener("dragenter", this._dragenter, false);
dropwrap.addeventlistener("dragover", this._dragover, false);
dropwrap.addeventlistener('drop', function(e){_this.readfile.call(_this,e)} , false);
log('window drop bind--ok');
},
_dragenter:function(e){e.stoppropagation();e.preventdefault();},
_dragover:function(e){e.stoppropagation();e.preventdefault();},
readfile:function(e){
e.stoppropagation();
e.preventdefault();
var dt = e.datatransfer;
var files = dt.files;
for(var i = 0; i< files.length;i++){
var html = html.slice();
html = this.writeheader(files[i], html);
this.read(files[i], html);
}
},
read:function(file, h){
var type = file.type;
var reader = new filereader();
reader.onprogress = function(e){
if (e.lengthcomputable){
log('progress: ' + math.ceil(100*e.loaded/file.size) +'%')
}
};
reader.onloadstart = function(e){
log('onloadstart: ok');
};
reader.onloadend = function(e){
var _result = e.target.result;
//console['log'](e.target);
log('data uri--ok');
var d = document.createelement('div');
h = h.replace('$filebase64$', _result);
if(/image/.test(file.type)){
h = h.replace('$data$',_result);
}
d.innerhtml = h;
document.getelementbyid('baseinfo').appendchild(d);
};
reader.readasdataurl(file); // base 64 编码
return;
},
writeheader:function(file, h){
log(file.filename + '+' + (file.size/1024));
return h.replace('$filename$', file.filename).replace("$filesize$",(file.size/1024)+'kb').replace("$filetype$",file.type);
}
}
new dp();
})()
// --></script>
</body>
</html>filereader对象
var filereader = new filereader();
filereader.onloadend = function(){
console.log(this.readystate); // 这个时候 应该是 2
console.log(this.result); 读取完成回调函数,数据保存在result中
}
filereader.readasbinarystring(file);// 开始读取2进制数据 异步 参数为file 对象
//filereader.readasdataurl(file); // 读取base64
//filereader.readastext(file);//读取文本信息
可以运行下面简单的例子(chrome 和 firefox 有效)
linux下memcache服务器端的安装
服务器端主要是安装memcache服务器端,目前的最新版本是 memcached-1.3.0 。
下载:http://www.danga.com/memcached/dist/memcached-1.2.2.tar.gz
另外,memcache用到了libevent这个库用于socket的处理,所以还需要安装libevent,libevent的最新版本是libevent-1.3。(如果你的系统已经安装了libevent,可以不用安装)
官网:http://www.monkey.org/~provos/libevent/
下载:http://www.monkey.org/~provos/libevent-1.3.tar.gz
用wget指令直接下载这两个东西.下载回源文件后。
1.先安装libevent。这个东西在配置时需要指定一个安装路径,即./configure –prefix=/usr;然后make;然后make install;
2.再安装memcached,只是需要在配置时需要指定libevent的安装路径即./configure –with-libevent=/usr;然后make;然后make install;
这样就完成了linux下memcache服务器端的安装。详细的方法如下:
1.分别把memcached和libevent下载回来,放到 /tmp 目录下:
# cd /tmp
# wget http://www.danga.com/memcached/dist/memcached-1.2.0.tar.gz
# wget http://www.monkey.org/~provos/libevent-1.2.tar.gz2.先安装libevent:
# tar zxvf libevent-1.2.tar.gz
# cd libevent-1.2
# ./configure –prefix=/usr
# make
# make install
(注:在这里执行的时候出现错误:
1,no acceptable c compiler found in $path
由于centos默认没有安装gcc,使用yum安装
#yum install gcc* make*
)
3.测试libevent是否安装成功:
# ls -al /usr/lib | grep libevent
lrwxrwxrwx 1 root root 21 11?? 12 17:38 libevent-1.2.so.1 -> libevent-1.2.so.1.0.3
-rwxr-xr-x 1 root root 263546 11?? 12 17:38 libevent-1.2.so.1.0.3
-rw-r–r– 1 root root 454156 11?? 12 17:38 libevent.a
-rwxr-xr-x 1 root root 811 11?? 12 17:38 libevent.la
lrwxrwxrwx 1 root root 21 11?? 12 17:38 libevent.so -> libevent-1.2.so.1.0.3
还不错,都安装上了。
4.安装memcached,同时需要安装中指定libevent的安装位置:
# cd /tmp
# tar zxvf memcached-1.2.0.tar.gz
# cd memcached-1.2.0
# ./configure –with-libevent=/usr
# make
# make install
如果中间出现报错,请仔细检查错误信息,按照错误信息来配置或者增加相应的库或者路径。
(注:安装的时候出现错误:
1 linux警告:检测到时钟错误。您的创建可能是不完整的
解决方法:
修改当前时间:
[root]#date –s ‘2010/11/5 8:01:00 ‘
将当前系统时间写入cmos中去
#clock –w
)
安装完成后会把memcached放到 /usr/local/bin/memcached ,
5.测试是否成功安装memcached:
# ls -al /usr/local/bin/mem*
-rwxr-xr-x 1 root root 137986 11?? 12 17:39 /usr/local/bin/memcached
-rwxr-xr-x 1 root root 140179 11?? 12 17:39 /usr/local/bin/memcached-debug
安装memcache的php教程扩展
1.在http://pecl.php.net/package/memcache 选择相应想要下载的memcache版本。
2.安装php的memcache扩展
tar vxzf memcache-2.2.1.tgz
cd memcache-2.2.1
/usr/local/php/bin/phpize
./configure –enable-memcache –with-php-config=/usr/local/php/bin/php-config –with-zlib-dir
make
make install
(注:
1 phpize没有找到
解决方法:
centos是默认没有安装php-devel的
yum install php-devel
2 make: *** [memcache.lo] error 1
没有安装zlib
yum install zlib-devel
3 配置的命令改为:./configure --enable-memcache --with-php-config=/usr/bin/php-config --with-zlib-dir
其中enable和with前面是两个--
)
3.上述安装完后会有类似这样的提示:
installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-non-zts-2007xxxx/
4.把php.ini中的extension_dir = “./”修改为
extension_dir = “/usr/local/php/lib/php/extensions/no-debug-non-zts-2007xxxx/”
5.添加一行来载入memcache扩展:extension=memcache.so
memcached的基本设置:
1.启动memcache的服务器端:
# /usr/local/bin/memcached -d -m 10 -u root -l 192.168.0.200 -p 12000 -c 256 -p /tmp/memcached.pid
-d选项是启动一个守护进程,
-m是分配给memcache使用的内存数量,单位是mb,我这里是10mb,
-u是运行memcache的用户,我这里是root,
-l是监听的服务器ip地址,如果有多个地址的话,我这里指定了服务器的ip地址192.168.0.200,
-p是设置memcache监听的端口,我这里设置了12000,最好是1024以上的端口,
-c选项是最大运行的并发连接数,默认是1024,我这里设置了256,按照你服务器的负载量来设定,
-p是设置保存memcache的pid文件,我这里是保存在 /tmp/memcached.pid,
(注:
1
出现错误:/usr/local/bin/memcached: error while loading shared libraries: libevent-1.3.so.1: cannot open shared object file: no such file or directory
直接设置链接
#ln -s /usr/local/libevent/lib/libevent-1.3.so.1 /lib64/libevent-1.3.so.1
)
2.如果要结束memcache进程,执行:
# kill `cat /tmp/memcached.pid`
也可以启动多个守护进程,不过端口不能重复。
3.重启apache,service httpd restart
memcache环境测试:
运行下面的php文件,如果有输出this is a test!,就表示环境搭建成功。开始领略memcache的魅力把!
< ?php
$mem = new memcache;
$mem->connect(“192.168.0.200 ”, 12000);
$mem->set(’key’, ‘this is a test!’, 0, 60);
$val = $mem->get(’key’);
echo $val;
?>
php教程利用cookie自动登录方法
<html>
<head>
<title>enter password</title>
</head>
<body>
<form name="forml" method="post" action="cookiebasedpasswordlogin.php">
<table>
<tr>
<td colspan="2" >
<div align="center"><b>please specify the password</b></div>
</td>
</tr>
<tr>>
<td>
<div align="right">customer id</div>
</td>
<td>
<input type="text" name="username">
</td>
</tr>
<tr>
<td>
<div align="right">password</div>
</td>
<td>
<input type="password" name="password">
</td>
</tr>
<tr>
<td colspan="2">
<center>
<input type="submit" name="submit" value="login">
</center>
</td>
</tr>
</table>
</form>
</body>
</html>
<!-- cookiebasedpasswordlogin.php
<?php
$now = getdate();
$storetime= $now["weekday"] . " " . $now["month"] ." " . $now["year"] ;
$storetime.=" time : ";if ($now["hours"] < 10) {
$storetime.= "0" . $now["hours"];
} else {
$storetime.= $now["hours"];
}
$storetime.= ":";
if ($now["minutes"]<10) {
$storetime.= "0" . $now["minutes"];
} else {
$storetime.= $now["minutes"];
}
$storetime.= ": ";
if ($now["seconds"] <10) {
$storetime.= "0" . $now["seconds"];
} else {
$storetime.= $now["seconds"];
}
if (isset($data)) {
$counter=++$data[l];
setcookie("data[0]",$storetime,time() + (60*60*24));
setcookie("data[l]", $counter,time() + (60*60*24)); setcookie("data[2]",$username,time() + (60*60*24));
echo "<b><center>hi " . $data[2] . " ! !</center></b><br>n";
echo "<b><center>last login time :" .$data[0] . "</center></b><br>n";
echo "<b><center>current date :" .$storetime. "</center></b><br>n";
echo "<b><center>page view count :" . $data[l]. "</center></b><br>n";
echo "<b><center>you have successfully logged in!</center></b>";
echo ("<b><contor>you can access this area without entering a password for the next 24 hours!</center></b>");
} else {
if (isset($username) && isset($password)) {
if ($password=="superpass") {
$counter=0;
setcookie("data[0]",$storetime,time() + (60*60*24));
setcookie("data[l]",$counter,time() + (60*60*24));
setcookie("data[2]",$username,time() + (60*60*24));
$url="location: cookieimp.php";
header($url);
}else{
echo "<hl><center>invalid password!!!</center></hl>";
}
}
}
?>
upload_err_ok no error occurred.
上传成功
upload_err_ini_size the uploaded file exceeds the maximum value specified in the php教程.ini file.
超出最大上传尺寸
upload_err_form_size the uploaded file exceeds the maximum value specified by the max_file_size hidden widget.
超出form设置最大上传尺寸
upload_err_partial the file upload was canceled and only part of the file was uploaded.
upload_err_nofile no file was uploaded.
未上传文件
<html>
<head>
<title>a simple file upload form</title>
</head>
<body>
<form enctype="multipart/form-data"
action="<?print $_server['php_self']?>" method="post">
<p>
<input type="hidden" name="max_file_size" value="102400" />
<input type="file" name="fupload" /><br/>
<input type="submit" value="upload!" />
</p>
</form>
</body>
</html>
实例一
]<html>
<head>
<title>a file upload script</title>
</head>
<body>
<div>
<?php
if ( isset( $_files['fupload'] ) ) {print "name: ". $_files['fupload']['name'] ."<br />";
print "size: ". $_files['fupload']['size'] ." bytes<br />";
print "temp name: ".$_files['fupload']['tmp_name'] ."<br />";
print "type: ". $_files['fupload']['type'] ."<br />";
print "error: ". $_files['fupload']['error'] ."<br />";if ( $_files['fupload']['type'] == "image/gif" ) {
$source = $_files['fupload']['tmp_name'];
$target = "upload/".$_files['fupload']['name'];
move_uploaded_file( $source, $target );// or die ("couldn't copy");
$size = getimagesize( $target );$imgstr = "<p><img width="$size[0]" height="$size[1]" ";
$imgstr .= "src="$target" alt="uploaded image" /></p>";print $imgstr;
}
}
?>
</div>
<form enctype="multipart/form-data"
action="<?php print $_server['php_self']?>" method="post">
<p>
<input type="hidden" name="max_file_size" value="102400" />
<input type="file" name="fupload" /><br/>
<input type="submit" value="upload!" />
</p>
</form>
</body>
</html>
文件上传实例二
<?php
$maxsize=28480;
if (!$http_post_vars['submit']) {
$error=" ";
}
if (!is_uploaded_file($http_post_files['upload_file']['tmp_name']) and !isset($error)) {
$error = "<b>you must upload a file!</b><br /><br />";
unlink($http_post_files['upload_file']['tmp_name']);
}
if ($http_post_files['upload_file']['size'] > $maxsize and !isset($error)) {
$error = "<b>error, file must be less than $maxsize bytes.</b><br /><br />";
unlink($http_post_files['upload_file']['tmp_name']);
}
if (!isset($error)) {
move_uploaded_file($http_post_files['upload_file']['tmp_name'],
"uploads/".$http_post_files['upload_file']['name']);
print "thank you for your upload.";
exit;
}
else
{
echo ("$error");
}
?><html>
<head></head>
<body>
<form action="<?php echo(htmlspecialchars($_server['php_self']))?>"
method="post" enctype="multipart/form-data">
choose a file to upload:<br />
<input type="file" name="upload_file" size="80">
<br />
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
php教程5中,变量的类型是不确定的,一个变量可以指向任何类型的数值、字符串、对象、资源等。我们无法说php5中多态的是变量。
我们只能说在php5中,多态应用在方法参数的类型提示位置。
一个类的任何子类对象都可以满足以当前类型作为类型提示的类型要求。所有实现这个接口的类,都可以满足以接口类型作为类型提示的方法参数要求。简单的说,一个类拥有其父类、和已实现接口的身份
通过实现接口实现多态
下面的例子中,useradmin类的静态方法,要求一个user类型的参数。
在后面的使用中,传递了一个实现了user接口的类normaluser的实例。代码成功运行。
<?
interface user{ // user接口
public function getname();
public function setname($_name);
}class normaluser implements user { // 实现接口的类.
private $name;
public function getname(){
return $this->name;
}
public function setname($_name){
$this->name = $_name;
}
}class useradmin{ //操作.
public static function changeusername(user $_user,$_username){
$_user->setname($_username);
}
}$normaluser = new normaluser();
useradmin::changeusername($normaluser,"tom");//这里传入的是 normaluser的实例.
echo $normaluser->getname();
?>
php 接口类:interface
其实他们的作用很简单,当有很多人一起开发一个项目时,可能都会去调用别人写的一些类,那你就会问,我怎么知道他的某个功能的实现方法是怎么命名的呢,这个时候php接口类就起到作用了,当我们定义了一个接口类时,它里面的方式是下面的子类必须实现的,比如 :
代码如下:
interface shop
{
public function buy($gid);
public function sell($gid);
public function view($gid);
}
我声明一个shop接口类,定义了三个方法:买(buy),卖(sell),看(view),那么继承此类的所有子类都必须实现这3个方法少一个都不行,如果子类没有实现这些话,就无法运行。实际上接口类说白了,就是一个类的模板,一个类的规定,如果你属于这类,你就必须遵循我的规定,少一个都不行,但是具体你怎么去做,我不管,那是你的事,如:
代码如下:
class baseshop implements shop
{
public function buy($gid)
{
echo('你购买了id为 :'.$gid.'的商品');
}
public function sell($gid)
{
echo('你卖了id为 :'.$gid.'的商品');
}
public function view($gid)
{
echo('你查看了id为 :'.$gid.'的商品');
}
}
下面缩一下方法
<?php
interface myusbkou
{
function type();//类型
function action();//执行的操作
}
class zip implements myusbkou
{ //继承接口
function type()
{
echo "usb的2.0接口";
}
function action()
{
echo "--->需要usb 2.0驱动";
}
}
class mp3 implements myusbkou
{
function type()
{
echo "mp3的1.0接口";
}
function action()
{
echo "--->需要mp3 1.0驱动<br/>";
}
}
class mypc
{
function usbthing($thing)
{
$thing->type();
$thing->action();
}
}
$p=new mypc();
$mp3=new mp3();
$zip=new zip();
$p->usbthing($mp3);
$p->usbthing($zip);
?>
相关文章
- 下面小编来给大家演示几个php操作zip文件的实例,我们可以读取zip包中指定文件与删除zip包中指定文件,下面来给大这介绍一下。 从zip压缩文件中提取文件 代...2016-11-25
Jupyter Notebook读取csv文件出现的问题及解决
这篇文章主要介绍了JupyterNotebook读取csv文件出现的问题及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2023-01-06- 有时我们接受或下载到的PSD文件打开是空白的,那么我们要如何来解决这个 问题了,下面一聚教程小伙伴就为各位介绍Photoshop打开PSD文件空白解决办法。 1、如我们打开...2016-09-14
- 这篇文章主要介绍了解决python 使用openpyxl读写大文件的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-13
- 这篇文章主要介绍了C#实现HTTP下载文件的方法,包括了HTTP通信的创建、本地文件的写入等,非常具有实用价值,需要的朋友可以参考下...2020-06-25
- 这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
- C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
php无刷新利用iframe实现页面无刷新上传文件(1/2)
利用form表单的target属性和iframe 一、上传文件的一个php教程方法。 该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失...2016-11-25- 本文章来人大家介绍一个php文件上传类的使用方法,期望此实例对各位php入门者会有不小帮助哦。 简介 Class.upload.php是用于管理上传文件的php文件上传类, 它可以帮...2016-11-25
- 要替换字符串中的内容我们只要利用php相关函数,如strstr,str_replace,正则表达式了,那么我们要替换目录所有文件的内容就需要先遍历目录再打开文件再利用上面讲的函数替...2016-11-25
- 又码了一个周末的代码,这次在做一些关于文件上传的东西。(PHP UPLOAD)小有收获项目是一个BT种子列表,用户有权限上传自己的种子,然后配合BT TRACK服务器把种子的信息写出来...2016-11-25
- 本文实例讲述了jQuery实现文件上传进度条效果的代码。分享给大家供大家参考。具体如下: 运行效果截图如下:具体代码如下:<!DOCTYPE html><html><head><meta charset="utf-8"><title>upload</title><link rel="stylesheet...2015-11-24
- 步骤:Window -> PHP -> Editor -> Templates,这里可以设置(增、删、改、导入等)管理你的模板。新建文件注释、函数注释、代码块等模板的实例新建模板,分别输入Name、Description、Patterna)文件注释Name: 3cfileDescriptio...2013-10-04
- 今天小编在这里就来给photoshop的这一款软件的使用者们来说下AI源文件转photoshop图像变模糊问题的解决教程,各位想知道具体解决方法的使用者们,那么下面就快来跟着小编...2016-09-14
- 这篇文章主要介绍了C++万能库头文件在vs中的安装步骤(图文),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-23
- 本篇文章主要说明的是与php文件上传的相关配置的知识点。PHP文件上传功能配置主要涉及php.ini配置文件中的upload_tmp_dir、upload_max_filesize、post_max_size等选项,下面一一说明。打开php.ini配置文件找到File Upl...2015-10-21
ant design中upload组件上传大文件,显示进度条进度的实例
这篇文章主要介绍了ant design中upload组件上传大文件,显示进度条进度的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-10-29- 这篇文章主要介绍了C#使用StreamWriter写入文件的方法,涉及C#中StreamWriter类操作文件的相关技巧,需要的朋友可以参考下...2020-06-25
- 举一个案例:复制代码 代码如下:<?phpclass Downfile { function downserver($file_name){$file_path = "./img/".$file_name;//转码,文件名转为gb2312解决中文乱码$file_name = iconv("utf-8","gb2312",$file_name...2014-06-07
- EXCEL数据上传到SQL SERVER中的方法需要注意到三点!注意点一:要把EXCEL数据上传到SQL SERVER中必须提前把EXCEL传到服务器上.做法: 在ASP.NET环境中,添加一个FileUpload上传控件后台代码的E.X: 复制代码 代码如下: if...2013-09-23