haidong 发表于 2010-2-24 13:37:44

·基于PHP的AJAX技术实现文件异步上传

<p>异步的文件上传是在现代的AJAX实现的Web应用里面经常要遇到,必须解决的问题。但是标准的AJAX类(XmlHttpRequest)无法实现传输文件的功能。因此,这里讨论的内容就是如何在AJAX的技术的基础之上构建异步的文件上传功能。在这个功能当中需要使用到内置的框及(IFRAME)来传输文件。这个功能实现的效果是页面在上传文件的时候,用户还可以使用该页面并且填写文件描述。 <br /><br />  这个例子是我们引用AJAX的经典案例进行分析的。<br /><br />  <strong>系统环境<br /></strong><br />  · 较新版本的浏览器。例如Opera,Firefox或者 <u><strong>Internet</strong></u> Explorer。 <br /><br />  · <u><strong>PHP</strong></u> 4.3.0 或更高版本 <br /><br />  · PHP 5 版本<br /><br />  · PHP 中的 'short_open_tag' 选项开启(否则会发生解析错误)。<br /><br />  <strong>功能分析</strong><br /><br />  通过内置的IFRAME(框架)进行文件上传。具备包括三个部分组成。<br /><br />  · 在页面中间有一个简单的<form...表单,表单只包含了<input type=&quot;file&quot; ... >控件。这个表单的目标链接就是一个隐藏得IFRAME(通过 <u><strong>CSS</strong></u>的风格&quot; display: none;&quot;实现)并且表单里面唯一一个控件的OnChange事件用来触发JavaScript函数。这个函数的作用是检查用户提交的扩展名,然后提交表单。 <br /><br />  · 在服务器端用PHP编写了一个处理过程(用FILEFRAME坐注释了)。这个处理过程用来把从客户端上传的文件进行检查后保存在服务器,并且通过Javascript代码的形式返回给用户。返回给用户的Javascript脚本通过&quot;parent.window.document&quot;更改了用户现在正在查看的页面,设置了文件的名称并启用了让用户提交表单的按钮。启用按钮的操作是通过getElementById函数实现的。<br /><br />  · 在主页面还有一个表单,它包含了用户提交的描述和隐藏的文件名。用户可以在文件上传的同时填写文件的描述。当文件上传结束以后,用户点击按钮,就可以看上传以后返回给用户的文件信息了。(通过返回来的文件名和用户输入的描述构成文件信息)。<br /><br />  可能你会说这么操作不符合常理:文件在用户确认之前就已经被提交了。如果用户没有提交的话,情况会如何呢。你可以自己在扩展处理被用户放弃的文件。 <br /><br />  这个例子把文件存储在一个文件系统的目录下。你需要在脚本开始运行的时候配置下这个目录,具体的包含这个目录信息的变量是&#36;upload_dir 和&#36;web_upload_dir。这里有一个对目录是否可写的权限检查。<br /><br />  这里我们用到了以下几个PHP函数:<br /><br />  · move_uploaded_file - 转移一经上传到服务器的文件 <br /><br />  · fopen - 打开文件 <br /><br />  · fwrite - 把内容写入文件 <br /><br />  · fclose - 关闭文件 <br /><br />  · str_replace - 替换字符串 <br /><br />  · filesize - 返回文件大小 <br /><br />  · filemtime - 返回处理时间<br /><br />  你可以通过手册查到这些函数如果使用。请注意要把HTM(<, >, &amp;)标记替换为(&amp;lt;, &amp;gt; 和 &amp;amp;).<p><br /><strong>   源代码<br /><br /></strong><table bordercolor="#cccccc" width="90%" align="center" bgcolor="#e7e9e9" border="1"><tr><td><?php<br />&#36;upload_dir = &quot;/var/www/anyexample/aeu&quot;; // 文件存储的路径<br />&#36;web_upload_dir = &quot;/aeu&quot;; // 文件在Web目录下的路径<br />&#36;tf = &#36;upload_dir.'/'.md5(rand()).&quot;.test&quot;;<br />&#36;f = @fopen(&#36;tf, &quot;w&quot;);<br />if (&#36;f == false) <br />die(&quot;Fatal error! {&#36;upload_dir} is not writable. Set 'chmod 777 {&#36;upload_dir}'<br />or something like this&quot;);<br />fclose(&#36;f);<br />unlink(&#36;tf);<br /><br />//处理上传的文件<br />if (isset(&#36;_POST['fileframe'])) <br />{<br /> &#36;result = 'ERROR';<br /> &#36;result_msg = 'No FILE field found';<br /><br /> if (isset(&#36;_FILES['file'])) // 从浏览器接受文件<br /> {<br />  if (&#36;_FILES['file']['error'] == UPLOAD_ERR_OK) // 没有错误<br />  {<br />   &#36;filename = &#36;_FILES['file']['name']; // 文件名 <br />   move_uploaded_file(&#36;_FILES['file']['tmp_name'], &#36;upload_dir.'/'.&#36;filename);<br />   // 处理的主过程-转移文件到 &#36;upload_dir <br />   &#36;result = 'OK';<br />  }<br />  elseif (&#36;_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)<br />   &#36;result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';<br />  else <br />   &#36;result_msg = 'Unknown error';<br /> }<br /><br /> echo '<html><head><title>-</title></head><body>';<br /> echo '<script language=&quot;JavaScript&quot; type=&quot;text/javascript&quot;>'.&quot;\n&quot;;<br /> echo 'var parDoc = window.parent.document;';<br /> '<br /> if (&#36;result == 'OK')<br /> {<br />  echo 'parDoc.getElementById(&quot;upload_status&quot;).value = &quot;file successfully uploaded&quot;;';<br />  echo 'parDoc.getElementById(&quot;filename&quot;).value = &quot;'.&#36;filename.'&quot;;';<br />  echo 'parDoc.getElementById(&quot;filenamei&quot;).value = &quot;'.&#36;filename.'&quot;;';<br />  echo 'parDoc.getElementById(&quot;upload_button&quot;).disabled = false;';<br /> }<br /> else<br /> {<br />  echo 'parDoc.getElementById(&quot;upload_status&quot;).value = &quot;ERROR: '.&#36;result_msg.'&quot;;';<br /> }<br /><br /> echo &quot;\n&quot;.'</script></body></html>';<br /> exit();<br />}<br /><br />function safehtml(&#36;s)<br />{<br /> &#36;s=str_replace(&quot;&amp;&quot;, &quot;&amp;amp;&quot;, &#36;s);<br /> &#36;s=str_replace(&quot;<&quot;, &quot;&amp;lt;&quot;, &#36;s);<br /> &#36;s=str_replace(&quot;>&quot;, &quot;&amp;gt;&quot;, &#36;s);<br /> &#36;s=str_replace(&quot;'&quot;, &quot;&amp;apos;&quot;, &#36;s);<br /> &#36;s=str_replace(&quot;\&quot;&quot;, &quot;&amp;quot;&quot;, &#36;s);<br /> return &#36;s;<br />}<br /><br />if (isset(&#36;_POST['description']))<br />{<br /> &#36;filename = &#36;_POST['filename'];<br /> &#36;size = filesize(&#36;upload_dir.'/'.&#36;filename);<br /> &#36;date = date('r', filemtime(&#36;upload_dir.'/'.&#36;filename));<br /> &#36;description = safehtml(&#36;_POST['description']);<br /><br /> &#36;html =<<<END<br /> <html><head><title>{&#36;filename} </title></head><br /> <body><br />  <h1>{&#36;filename}</h1><br />  <p>This is a file information page for your uploaded file. Bookmark it,_or_send to anyone...</p><br />  <p>Date: {&#36;date}</p><br />  <p>Size: {&#36;size} bytes</p><br />  <p>Description: <br />  <pre>{&#36;description}</pre><br />  </p><br />  <p><a href=&quot;{&#36;web_upload_dir}/{&#36;filename}&quot; style=&quot;font-size: large;&quot;>download file</a><br><br />  <a href=&quot;{&#36;PHP_SELF}&quot; style=&quot;font-size: small;&quot;>back to file uploading</a><br><br />  <a href=&quot;{&#36;web_upload_dir}/upload-log.html&quot; style=&quot;font-size: small;&quot;>upload-log</a></p><br />  <br><br>Example by <a href=&quot;http://www.anyexample.com/&quot;>AnyExample</a><br /> </body></html><br /> END;<br /> <br /> &#36;f = fopen(&#36;upload_dir.'/'.&#36;filename.'-desc.html', &quot;w&quot;);<br /> fwrite(&#36;f, &#36;html);<br /> fclose(&#36;f);<br /> &#36;msg = &quot;File {&#36;filename} uploaded, <br /> <a href='{&#36;web_upload_dir}/{&#36;filename}-desc.html'>see file information page</a>&quot;;<br /><br /> &#36;f = fopen(&#36;upload_dir.&quot;/upload-log.html&quot;, &quot;a&quot;);<br /> fwrite(&#36;f, &quot;<p>&#36;msg</p>\n&quot;);<br /> fclose(&#36;f);<br /><br /> setcookie('msg', &#36;msg); <br /> header(&quot;Location: http://&quot;.&#36;_SERVER['HTTP_HOST'].&#36;PHP_SELF); <br /> exit(); <br />} <br /><br />if (isset(&#36;_COOKIE['msg']) &amp;&amp; &#36;_COOKIE['msg'] != '') <br />{ <br /> if (get_magic_quotes_gpc()) <br />  &#36;msg = stripslashes(&#36;_COOKIE['msg']); <br /> else<br />  &#36;msg = &#36;_COOKIE['msg'];<br />  setcookie('msg', ''); <br />} <br />?><br /><!-- Beginning of main page --><br /><html><head><br /><title>IFRAME Async file uploader example</title><br /></head><br /><body><br /><?php <br /> if (isset(&#36;msg)) <br />  echo '<p style=&quot;font-weight: bold;&quot;>'.&#36;msg.'</p>';<br />?> <br /><h1>Upload file:</h1><br /><p>File will begin to upload just after selection. </p><br /><p>You may write file description, while you file is being uploaded.</p><br /><br /><form action=&quot;<?=&#36;PHP_SELF?>&quot; target=&quot;upload_iframe&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;><br /> <input type=&quot;hidden&quot; name=&quot;fileframe&quot; value=&quot;true&quot;><br /> <!-- Target of the form is set to hidden iframe --><br /> <!-- From will send its post data to fileframe section of this PHP script (see above) --><br /><br /> <label for=&quot;file&quot;>text file uploader:</label><br><br /> <!-- JavaScript is called by OnChange attribute --><br /> <input type=&quot;file&quot; name=&quot;file&quot; id=&quot;file&quot; onChange=&quot;jsUpload(this)&quot;><br /></form><br /><script type=&quot;text/javascript&quot;><br />/* This function is called when user selects file in file dialog */<br />function jsUpload(upload_field)<br />{<br /> // this is just an example of checking file extensions<br /> // if you do not need extension checking, remove <br /> // everything down to line<br /> // upload_field.form.submit();<br /> <br /> var re_text = /\.txt|\.xml|\.zip/i;<br /> var filename = upload_field.value;<br /><br /> /* Checking file type */<br /> if (filename.search(re_text) == -1)<br /> {<br />  alert(&quot;File does not have text(txt, xml, zip) extension&quot;);<br />  upload_field.form.reset();<br />  return false;<br /> }<br /><br /> upload_field.form.submit();<br /> document.getElementById('upload_status').value = &quot;uploading file...&quot;;<br /> upload_field.disabled = true;<br /> return true;<br />}<br /></script><br /><iframe name=&quot;upload_iframe&quot; style=&quot;width: 400px; height: 100px; display: none;&quot;><br /></iframe><br /><!-- For debugging purposes, it's often useful to remove<br />&quot;display: none&quot; from style=&quot;&quot; attribute --><br /><br /><br><br />Upload status:<br><br /><input type=&quot;text&quot; name=&quot;upload_status&quot; id=&quot;upload_status&quot; <br />value=&quot;not uploaded&quot; size=&quot;64&quot; disabled><br /><br><br><br /><br />File name:<br><br /><input type=&quot;text&quot; name=&quot;filenamei&quot; id=&quot;filenamei&quot; value=&quot;none&quot; disabled><br /><br /><form action=&quot;<?=&#36;PHP_SELF?>&quot; method=&quot;POST&quot;><br /> <!-- one field is &quot;disabled&quot; for displaying-only. Other, hidden one is for sending data --><br /> <input type=&quot;hidden&quot; name=&quot;filename&quot; id=&quot;filename&quot;><br /> <br><br><br /><br /> <label for=&quot;photo&quot;>File description:</label><br><br /> <textarea rows=&quot;5&quot; cols=&quot;50&quot; name=&quot;description&quot;></textarea><br /><br /> <br><br><br /> <input type=&quot;submit&quot; id=&quot;upload_button&quot; value=&quot;save file&quot; disabled><br /></form><br /><br><br><br /><a href=&quot;<?=&#36;web_upload_dir?>/upload-log.html&quot;>upload-log</a><br /><br><br><br><br /><br />Example by <a href=&quot;http://www.anyexample.com/&quot;>AnyExample</a><br /></body><br /></html></td></tr></table><br />  以上的讲解就是提供一种思路供大家参考。大家也可以根据自己的需求进行相应的优化。</p></p>
页: [1]
查看完整版本: ·基于PHP的AJAX技术实现文件异步上传