|
异步的文件上传是在现代的AJAX实现的Web应用里面经常要遇到,必须解决的问题。但是标准的AJAX类(XmlHttpRequest)无法实现传输文件的功能。因此,这里讨论的内容就是如何在AJAX的技术的基础之上构建异步的文件上传功能。在这个功能当中需要使用到内置的框及(IFRAME)来传输文件。这个功能实现的效果是页面在上传文件的时候,用户还可以使用该页面并且填写文件描述。 < > 这个例子是我们引用AJAX的经典案例进行分析的。</P>< > 系统环境</P>< > · 较新版本的浏览器。例如Opera,Firefox或者 Internet Explorer。 </P>< > · PHP 4.3.0 或更高版本 </P>< > · PHP 5 版本</P>< > · PHP 中的 'short_open_tag' 选项开启(否则会发生解析错误)。</P>< > 功能分析</P>< > 通过内置的IFRAME(框架)进行文件上传。具备包括三个部分组成。</P>< > · 在页面中间有一个简单的<form...表单,表单只包含了<input type="file" ... >控件。这个表单的目标链接就是一个隐藏得IFRAME(通过 CSS的风格" display: none;"实现)并且表单里面唯一一个控件的OnChange事件用来触发JavaScript函数。这个函数的作用是检查用户提交的扩展名,然后提交表单。 </P>< > · 在服务器端用PHP编写了一个处理过程(用FILEFRAME坐注释了)。这个处理过程用来把从客户端上传的文件进行检查后保存在服务器,并且通过Javascript代码的形式返回给用户。返回给用户的Javascript脚本通过"parent.window.document"更改了用户现在正在查看的页面,设置了文件的名称并启用了让用户提交表单的按钮。启用按钮的操作是通过getElementById函数实现的。</P>< > · 在主页面还有一个表单,它包含了用户提交的描述和隐藏的文件名。用户可以在文件上传的同时填写文件的描述。当文件上传结束以后,用户点击按钮,就可以看上传以后返回给用户的文件信息了。(通过返回来的文件名和用户输入的描述构成文件信息)。</P>< > 可能你会说这么操作不符合常理:文件在用户确认之前就已经被提交了。如果用户没有提交的话,情况会如何呢。你可以自己在扩展处理被用户放弃的文件。 </P>< > 这个例子把文件存储在一个文件系统的目录下。你需要在脚本开始运行的时候配置下这个目录,具体的包含这个目录信息的变量是$upload_dir 和$web_upload_dir。这里有一个对目录是否可写的权限检查。</P>< > 这里我们用到了以下几个PHP函数:</P>< > · move_uploaded_file - 转移一经上传到服务器的文件 </P>< > · fopen - 打开文件 </P>< > · fwrite - 把内容写入文件 </P>< > · fclose - 关闭文件 </P>< > · str_replace - 替换字符串 </P>< > · filesize - 返回文件大小 </P>< > · filemtime - 返回处理时间</P>< > 你可以通过手册查到这些函数如果使用。请注意要把HTM(<, >, &)标记替换为(&lt;, &gt; 和 &amp;).</P>< ><TABLE style="BORDER-RIGHT: #999 1px solid; BORDER-TOP: #999 1px solid; FONT-SIZE: 12px; BORDER-LEFT: #999 1px solid; WIDTH: 80%; BORDER-BOTTOM: #999 1px solid" align=center><TBODY><TR><TD>< ><?php<BR>$upload_dir = "/var/www/anyexample/aeu"; // 文件存储的路径<BR>$web_upload_dir = "/aeu"; // 文件在Web目录下的路径<BR>$tf = $upload_dir.'/'.md5(rand()).".test";<BR>$f = @fopen($tf, "w");<BR>if ($f == false) <BR>die("Fatal error! {$upload_dir} is not writable. Set 'chmod 777 {$upload_dir}'<BR>or something like this");<BR>fclose($f);<BR>unlink($tf);</P>< >//处理上传的文件<BR>if (isset($_POST['fileframe'])) <BR>{<BR> $result = 'ERROR';<BR> $result_msg = 'No FILE field found';</P>< > if (isset($_FILES['file'])) // 从浏览器接受文件<BR> {<BR> if ($_FILES['file']['error'] == UPLOAD_ERR_OK) // 没有错误<BR> {<BR> $filename = $_FILES['file']['name']; // 文件名 <BR> move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.'/'.$filename);<BR> // 处理的主过程-转移文件到 $upload_dir <BR> $result = 'OK';<BR> }<BR> elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)<BR> $result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';<BR> else <BR> $result_msg = 'Unknown error';<BR> }</P>< > echo '<html><head><title>-</title></head><body>';<BR> echo '<script language="JavaScript" type="text/javascript">'."\n";<BR> echo 'var parDoc = window.parent.document;';<BR> '<BR> if ($result == 'OK')<BR> {<BR> echo 'parDoc.getElementById("upload_status").value = "file successfully uploaded";';<BR> echo 'parDoc.getElementById("filename").value = "'.$filename.'";';<BR> echo 'parDoc.getElementById("filenamei").value = "'.$filename.'";';<BR> echo 'parDoc.getElementById("upload_button").disabled = false;';<BR> }<BR> else<BR> {<BR> echo 'parDoc.getElementById("upload_status").value = "ERROR: '.$result_msg.'";';<BR> }</P>< > echo "\n".'</script></body></html>';<BR> exit();<BR>}</P>< >function safehtml($s)<BR>{<BR> $s=str_replace("&", "&amp;", $s);<BR> $s=str_replace("<", "&lt;", $s);<BR> $s=str_replace(">", "&gt;", $s);<BR> $s=str_replace("'", "&apos;", $s);<BR> $s=str_replace("\"", "&quot;", $s);<BR> return $s;<BR>}</P>< >if (isset($_POST['description']))<BR>{<BR> $filename = $_POST['filename'];<BR> $size = filesize($upload_dir.'/'.$filename);<BR> $date = date('r', filemtime($upload_dir.'/'.$filename));<BR> $description = safehtml($_POST['description']);</P>< > $html =<<<END<BR> <html><head><title>{$filename} [uploaded by IFRAME Async file uploader]</title></head><BR> <body><BR> <h1>{$filename}</h1><BR> <p>This is a file information page for your uploaded file. Bookmark it,_or_send to anyone...</p><BR> <p>Date: {$date}</p><BR> <p>Size: {$size} bytes</p><BR> <p>Description: <BR> <pre>{$description}</pre><BR> </p><BR> <p><a href="{$web_upload_dir}/{$filename}" style="font-size: large;">download file</a><br><BR> <a href="{$PHP_SELF}" style="font-size: small;">back to file uploading</a><br><BR> <a href="{$web_upload_dir}/upload-log.html" style="font-size: small;">upload-log</a></p><BR> <br><br>Example by <a href="<A href="http://www.anyexample.com/"><U><FONT color=#0066cc>http://www.anyexample.com/</FONT></U></A>">AnyExample</a><BR> </body></html><BR> END;<BR> <BR> $f = fopen($upload_dir.'/'.$filename.'-desc.html', "w");<BR> fwrite($f, $html);<BR> fclose($f);<BR> $msg = "File {$filename} uploaded, <BR> <a href='{$web_upload_dir}/{$filename}-desc.html'>see file information page</a>";</P>< > $f = fopen($upload_dir."/upload-log.html", "a");<BR> fwrite($f, "<p>$msg</p>\n");<BR> fclose($f);</P>< > setcookie('msg', $msg); <BR> header("Location: <A href="http://%22.$_server['http_host'].$php_self/"><U><FONT color=#0066cc>http://".$_SERVER['HTTP_HOST'].$PHP_SELF</FONT></U></A>); <BR> exit(); <BR>} </P>< >if (isset($_COOKIE['msg']) && $_COOKIE['msg'] != '') <BR>{ <BR> if (get_magic_quotes_gpc()) <BR> $msg = stripslashes($_COOKIE['msg']); <BR> else<BR> $msg = $_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($msg)) <BR> echo '<p style="font-weight: bold;">'.$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></P>< ><form action="<?=$PHP_SELF?>" target="upload_iframe" method="post" enctype="multipart/form-data"><BR> <input type="hidden" name="fileframe" value="true"><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) --></P>< > <label for="file">text file uploader:</label><br><BR> <!-- JavaScript is called by OnChange attribute --><BR> <input type="file" name="file" id="file" onChange="jsUpload(this)"><BR></form><BR><script type="text/javascript"><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;</P>< > /* Checking file type */<BR> if (filename.search(re_text) == -1)<BR> {<BR> alert("File does not have text(txt, xml, zip) extension");<BR> upload_field.form.reset();<BR> return false;<BR> }</P>< > upload_field.form.submit();<BR> document.getElementById('upload_status').value = "uploading file...";<BR> upload_field.disabled = true;<BR> return true;<BR>}<BR></script><BR><iframe name="upload_iframe" style="width: 400px; height: 100px; display: none;"><BR></iframe><BR><!-- For debugging purposes, it's often useful to remove<BR>"display: none" from style="" attribute --></P>< ><br><BR>Upload status:<br><BR><input type="text" name="upload_status" id="upload_status" <BR>value="not uploaded" size="64" disabled><BR><br><br></P>< >File name:<br><BR><input type="text" name="filenamei" id="filenamei" value="none" disabled></P>< ><form action="<?=$PHP_SELF?>" method=" OST"><BR> <!-- one field is "disabled" for displaying-only. Other, hidden one is for sending data --><BR> <input type="hidden" name="filename" id="filename"><BR> <br><br></P>< > <label for="photo">File description:</label><br><BR> <textarea rows="5" cols="50" name="description"></textarea></P>< > <br><br><BR> <input type="submit" id="upload_button" value="save file" disabled><BR></form><BR><br><br><BR><a href="<?=$web_upload_dir?>/upload-log.html">upload-log</a><BR><br><br><br></P>< >Example by <a href="<A href="http://www.anyexample.com/"><U><FONT color=#0066cc>http://www.anyexample.com/</FONT></U></A>">AnyExample</a><BR></body><BR></html></P></TD></TR></TBODY></TABLE></P><BR><SCRIPT type=text/javascript><!--google_ad_client = "pub-3758674625497328";google_ad_width = 180;google_ad_height = 150;google_ad_format = "180x150_as";google_ad_type = "text_image";//2007-04-07: space.chinaphp.orggoogle_ad_channel = "1445307639";google_color_border = "FFFFFF";google_color_bg = "F7F7F7";google_color_link = "000000";google_color_text = "000000";google_color_url = "3399CC";//--></SCRIPT><SCRIPT src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type=text/javascript></SCRIPT> |
|