基於PHP的AJAX技術實現檔案非同步上傳

來源:互聯網
上載者:User
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" >
</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.xrss.cn/">AnyExample</a>
</body>
</html>

  以上的講解就是提供一種思路供大家參考。大家也可以根據自己的需求進行相應的最佳化。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.