电脑安全

您当前的位置:主页 > 电脑安全 >

PHP的AJAX技术实现文件异步上传-网络编程

来源:[db:来源]标题:   文件    编辑:电脑技术全能网 时间:2019-09-23 12:34

原标题:PHP的AJAX技术实现文件异步上传-网络编程
   异步的文件上传是在古代的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("'", "'", $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>

上一篇:php经典分页函数_适合初学才-网络编程

下一篇:没有了