All articles| All Pictures| All Softwares| All Video| Go home page| Write articles| Upload pictures

Reading number is top 10 articles
WCF分布式开发常见错误:-Unrecognized,attribute,’targetFramework’,(未识别的属性’targetFramework’,)_.net资料_编程技术
通过内存配置来优化SQL Server的性能_[SQL Server教程]
SQL游标原理和使用方法_mssql学习_编程技术
PHP+MYSQL实例:网站在线人数的程序代码_php资料_编程技术
序列化和反序列化XML应用程序设置类_[Asp.Net教程]
LINQ体验(14)——LINQ,to,SQL语句之存储过程_[Asp.Net教程]
网站提高百度收录的五种方法_百度优化_seo学堂
解决Ajax中文乱码问题_[AJAX教程]
SQL操作全集(部分是Mssql语句,不在access中使用)_[SQL Server教程]
ASP.NET,2.0,Membership原理及应用_.net资料_编程技术
Reading number is top 10 pictures
2013中国四川省高考作文
世界各国15岁的MM有什么不同
This is heaven to some path
The sixties of the last century, China is such a kill pig
这才叫绝色美女2
The money of more than 100 countries and regions20
The world first motorcycle will be auctioned for 21000 pounds
奇趣的世界记录1
29 the belle stars after bath figure4
美女浴室写真3
Download software ranking
网页特效实例大全
WebService在.NET中的实战应用教学视频 → 第1集
Unix video tutorial3
Boxer's Top ten classic battle8
Boxer's Top ten classic battle6
美女写真1
Macromedia Dreamweaver 8
Unix video tutorial7
XML+Web+Service开发教程
Tram sex maniac 2 (H) rar bag2
aaa published in(发表于) 2013/12/27 20:03:31 Edit(编辑)
基于PHP的AJAX技术实现文件异步上传_php资料_编程技术

基于PHP的AJAX技术实现文件异步上传_php资料_编程技术

基于PHP的AJAX技术实现文件异步上传_php资料_编程技术-你的首页-uuhomepage.com

  异步的文件上传是在现代的AJAX实现的Web应用里面经常要遇到,必须解决的问题。但是标准的AJAX类(XmlHttpRequest)无法实现传输文件的功能。因此,这里讨论的内容就是如何在AJAX的技术的基础之上构建异步的文件上传功能。在这个功能当中需要使用到内置的框及(IFRAME)来传输文件。这个功能实现的效果是页面在上传文件的时候,用户还可以使用该页面并且填写文件描述。

  这个例子是我们引用AJAX的经典案例进行分析的。

  系统环境

  · 较新版本的浏览器。例如Opera,Firefox或者 Internet Explorer。

  · PHP 4.3.0 或更高版本

  · PHP 5 版本

  · PHP 中的 'short_open_tag' 选项开启(否则会发生解析错误)。

  功能分析

  通过内置的IFRAME(框架)进行文件上传。具备包括三个部分组成。

  · 在页面中间有一个简单的<form...表单,表单只包含了<input type="file" ... >控件。这个表单的目标链接就是一个隐藏得IFRAME(通过 CSS的风格" display: none;"实现)并且表单里面唯一一个控件的OnChange事件用来触发javascript函数。这个函数的作用是检查用户提交的扩展名,然后提交表单。

  · 在服务器端用PHP编写了一个处理过程(用FILEFRAME坐注释了)。这个处理过程用来把从客户端上传的文件进行检查后保存在服务器,并且通过javascript代码的形式返回给用户。返回给用户的javascript脚本通过"parent.window.document"更改了用户现在正在查看的页面,设置了文件的名称并启用了让用户提交表单的按钮。启用按钮的操作是通过getElementById函数实现的。

  · 在主页面还有一个表单,它包含了用户提交的描述和隐藏的文件名。用户可以在文件上传的同时填写文件的描述。当文件上传结束以后,用户点击按钮,就可以看上传以后返回给用户的文件信息了。(通过返回来的文件名和用户输入的描述构成文件信息)。

  可能你会说这么操作不符合常理:文件在用户确认之前就已经被提交了。如果用户没有提交的话,情况会如何呢。你可以自己在扩展处理被用户放弃的文件。

  这个例子把文件存储在一个文件系统的目录下。你需要在脚本开始运行的时候配置下这个目录,具体的包含这个目录信息的变量是$upload_dir 和$web_upload_dir。这里有一个对目录是否可写的权限检查。

  这里我们用到了以下几个PHP函数:

  · move_uploaded_file - 转移一经上传到服务器的文件

  · fopen - 打开文件

  · fwrite - 把内容写入文件

  · fclose - 关闭文件

  · str_replace - 替换字符串

  · filesize - 返回文件大小

  · filemtime - 返回处理时间

  你可以通过手册查到这些函数如果使用。请注意要把HTM(<, >, &)标记替换为(<, > 和 &).

  源代码


<?php
$upload_dir = "/var/www/anyexample/aeu"; // 文件存储的路径
$web_upload_dir = "/aeu"; // 文件在Web目录下的路径
$tf = $upload_dir.'/'.md5(rand()).".test";
$f = @fopen($tf, "w");
if ($f == false)
die("Fatal error! {$upload_dir} is not writable. Set 'chmod 777 {$upload_dir}'
or something like this");
fclose($f);
unlink($tf);

//处理上传的文件
if (isset($_POST['fileframe']))
{
 $result = 'ERROR';
 $result_msg = 'No FILE field found';

 if (isset($_FILES['file'])) // 从浏览器接受文件
 {
  if ($_FILES['file']['error'] == UPLOAD_ERR_OK) // 没有错误
  {
   $filename = $_FILES['file']['name']; // 文件名
   move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.'/'.$filename);
   // 处理的主过程-转移文件到 $upload_dir
   $result = 'OK';
  }
  elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)
   $result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
  else
   $result_msg = 'Unknown error';
 }

 echo '<html><head><title>-</title></head><body>';
 echo '<script language="javascript" type="text/javascript">'."\n";
 echo 'var parDoc = window.parent.document;';
 '
 if ($result == 'OK')
 {
  echo 'parDoc.getElementById("upload_status").value = "file successfully uploaded";';
  echo 'parDoc.getElementById("filename").value = "'.$filename.'";';
  echo 'parDoc.getElementById("filenamei").value = "'.$filename.'";';
  echo 'parDoc.getElementById("upload_button").disabled = false;';
 }
 else
 {
  echo 'parDoc.getElementById("upload_status").value = "ERROR: '.$result_msg.'";';
 }

 echo "\n".'</script></body></html>';
 exit();
}

function safehtml($s)
{
 $s=str_replace("&", "&", $s);
 $s=str_replace("<", "<", $s);
 $s=str_replace(">", ">", $s);
 $s=str_replace("'", "&apos;", $s);
 $s=str_replace("\"", """, $s);
 return $s;
}

if (isset($_POST['description']))
{
 $filename = $_POST['filename'];
 $size = filesize($upload_dir.'/'.$filename);
 $date = date('r', filemtime($upload_dir.'/'.$filename));
 $description = safehtml($_POST['description']);

 $html =<<<END
 <html><head><title>{$filename} [uploaded by IFRAME Async file uploader]</title></head>
 <body>
  <h1>{$filename}</h1>
  <p>This is a file information page for your uploaded file. Bookmark it, or send to anyone...</p>
  <p>Date: {$date}</p>
  <p>Size: {$size} bytes</p>
  <p>Description:
  <pre>{$description}</pre>
  </p>
  <p><a href="{$web_upload_dir}/{$filename}" style="font-size: large;">download file</a><br>
  <a href="{$PHP_SELF}" style="font-size: small;">back to file uploading</a><br>
  <a href="{$web_upload_dir}/upload-log.html" style="font-size: small;">upload-log</a></p>
  <br><br>Example by <a href="http://www.anyexample.com/">AnyExample</a>
 </body></html>
 END;
 
 $f = fopen($upload_dir.'/'.$filename.'-desc.html', "w");
 fwrite($f, $html);
 fclose($f);
 $msg = "File {$filename} uploaded,
 <a href='{$web_upload_dir}/{$filename}-desc.html'>see file information page</a>";

 $f = fopen($upload_dir."/upload-log.html", "a");
 fwrite($f, "<p>$msg</p>\n");
 fclose($f);

 setcookie('msg', $msg);
 header("Location: http://".$_SERVER['HTTP_HOST'].$PHP_SELF);
 exit();
}

if (isset($_COOKIE['msg']) && $_COOKIE['msg'] != '')
{
 if (get_magic_quotes_gpc())
  $msg = stripslashes($_COOKIE['msg']);
 else
  $msg = $_COOKIE['msg'];
  setcookie('msg', '');
}
?>
<!-- Beginning of main page -->
<html><head>
<title>IFRAME Async file uploader example</title>
</head>
<body>
<?php
 if (isset($msg))
  echo '<p style="font-weight: bold;">'.$msg.'</p>';
?>
<h1>Upload file:</h1>
<p>File will begin to upload just after selection. </p>
<p>You may write file description, while you file is being uploaded.</p>

<form action="<?=$PHP_SELF?>" target="upload_iframe" method="post" enctype="multipart/form-data">
 <input type="hidden" name="fileframe" value="true">
 <!-- Target of the form is set to hidden iframe -->
 <!-- From will send its post data to fileframe section of this PHP script (see above) -->

 <label for="file">text file uploader:</label><br>
 <!-- javascript is called by OnChange attribute -->
 <input type="file" name="file" id="file" onChange="jsUpload(this)">
</form>
<script type="text/javascript">
/* This function is called when user selects file in file dialog */
function jsUpload(upload_field)
{
 // this is just an example of checking file extensions
 // if you do not need extension checking, remove
 // everything down to line
 // upload_field.form.submit();
 
 var re_text = /\.txt|\.xml|\.zip/i;
 var filename = upload_field.value;

 /* Checking file type */
 if (filename.search(re_text) == -1)
 {
  alert("File does not have text(txt, xml, zip) extension");
  upload_field.form.reset();
  return false;
 }

 upload_field.form.submit();
 document.getElementById('upload_status').value = "uploading file...";
 upload_field.disabled = true;
 return true;
}
</script>
<iframe name="upload_iframe" style="width: 400px; height: 100px; display: none;">
</iframe>
<!-- For debugging purposes, it's often useful to remove
"display: none" from style="" attribute -->

<br>
Upload status:<br>
<input type="text" name="upload_status" id="upload_status"
value="not uploaded" size="64" disabled>
<br><br>

File name:<br>
<input type="text" name="filenamei" id="filenamei" value="none" disabled>

<form action="<?=$PHP_SELF?>" method="POST">
 <!-- one field is "disabled" for displaying-only. Other, hidden one is for sending data -->
 <input type="hidden" name="filename" id="filename">
 <br><br>

 <label for="photo">File description:</label><br>
 <textarea rows="5" cols="50" name="description"></textarea>

 <br><br>
 <input type="submit" id="upload_button" value="save file" disabled>
</form>
<br><br>
<a href="<?=$web_upload_dir?>/upload-log.html">upload-log</a>
<br><br><br>

Example by <a href="http://www.anyexample.com/">AnyExample</a>
</body>
</html>
  以上的讲解就是提供一种思路供大家参考。大家也可以根据自己的需求进行相应的优化。





添加到del.icio.us 添加到新浪ViVi 添加到百度搜藏 添加到POCO网摘 添加到天天网摘365Key 添加到和讯网摘 添加到天极网摘 添加到黑米书签 添加到QQ书签 添加到雅虎收藏 添加到奇客发现 diigo it 添加到饭否 添加到飞豆订阅 添加到抓虾收藏 添加到鲜果订阅 digg it 貼到funP 添加到有道阅读 Live Favorites 添加到Newsvine 打印本页 用Email发送本页 在Facebook上分享


Disclaimer Privacy Policy About us Site Map

If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.