標籤:
最近在搞一個livezilla的線上客服聊天的東東,客戶介面要求添加一個下載聊天記錄的功能。於是我就是翻看了下網上的各種關於”js儲存檔案至本地“的資料,發現只能在IE下通過execCommand實現。於是又是一番折騰啊。言歸正傳,下面開始上正餐。
html標籤
<td <!--FU_HIDDEN-->><a id="download" target="_blank" ><img class="lz_chat_clickable_image" onclick="top.savefile();" src="./images/button_file.gif" border="0" title="<!--lang_client_save_file-->" alt="<!--lang_client_save_file-->"></a></td>
js函數
function savefile(){var result=‘‘;var iframe = window.frames["lz_chat_frame.3.2"];var chatframe =iframe.document.all["lz_chat_frame.3.2.chat.4.0"].contentWindow.document;var topframe=iframe.document.all["lz_chat_frame.3.2.chat.0.0"].contentWindow.document;//text是從頁面上擷取到的聊天資訊var text = chatframe.getElementById(‘lz_chat_main‘).innerText;//對標籤添加串連屬性及其值topframe.getElementById(‘download‘).setAttribute("href","./chatnote.php?data="+text);}
方式一:通過一個a標籤,已get方式將資料傳到服務端,然後服務端建立檔案,儲存傳過來的內容,然後讀取檔案內容,最近進行下載操作。此方式主要是為了我熟悉一下php的建立檔案和讀取檔案。要是你需要直接下載的話,請查看第二種方式。
php代碼
<?php $dirname = date(‘Ymd‘,time()); $filename =date(‘YmdHis‘,time()); //在chatrecord目錄下建立命名為當前日期的檔案夾 $filepath = "chatrecord/".$dirname;mk_dir($filepath); // 迴圈建立目錄 function mk_dir($dir, $mode = 0755) { if (is_dir($dir) || @mkdir($dir,$mode)) return true; if (!mk_dir(dirname($dir),$mode)) return false; return @mkdir($dir,$mode); } //擷取內容header(‘Content-Type:text/html; charset=utf-8‘);$backValue=$_GET[‘data‘]; $filename = ‘chatrecord/‘.$dirname.‘/‘.$filename.‘.txt‘;//將內容寫入檔案$myfile = fopen($filename, "w") or die("Unable to open file!");fwrite($myfile, $backValue);fclose($myfile);$filesize = filesize($filename);$now =date(‘His‘,time());$downfilename =‘客服記錄‘.$now.‘.txt‘;//下載的檔案名稱header( "Content-Type: application/force-download ");header( "Content-Disposition: attachment; filename=".$downfilename);header( "Content-Length: ".$filesize);$data = file_get_contents($filename);//擷取檔案內容echo $data;?>
方式二:不在服務端儲存檔案,直接下載檔案
<?php //擷取內容header(‘Content-Type:text/html; charset=utf-8‘);$backValue=$_GET[‘data‘]; $now =date(‘His‘,time());$downfilename =‘客服記錄‘.$now.‘.txt‘;//下載的檔案名稱header( "Content-Type: application/force-download ");header( "Content-Disposition: attachment; filename=".$downfilename);$data = $backValue;//擷取檔案內容echo $data;?>
php中關於js儲存檔案至本地的問題