做個好看的HTML檔案上傳按鈕吧~_~

做個好看的HTML檔案上傳按鈕吧~_~
 
在網站與使用者互動日漸頻繁的今日,使用JavaScript增強前端網頁的互動性,
作為後端伺服器錯誤處理的先驅應用十分普及。
網頁設計師們更是努力表現出網頁的特殊風格。
然而,檔案上傳的HTML元件往往還是醜陋的系統預設外觀,
且檔案上傳欄位也無法以JavaScript阻止使用者隨意填入錯誤資料,
更增加了後端伺服程式的錯誤處理壓力。
 
我們用JavaScript技術來做個好看點的檔案上傳按鈕吧。
原理如下:
  1. 放個一般的檔案上傳物件,用css把它藏起來不讓使用者看到。
  2. 放個一般的文字輸入物件,用JavaScript設定為不可key in資料。
  3. 做個連結出來,看要用陽春的文字還是漂亮的圖案都可以。
  4. 當按下此連結時呼叫選取上傳檔案的對話方塊。
  5. 把取得的檔案名稱顯示在一般文字輸入物件。

範例程式碼如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title>JavaScript呼叫檔案上傳對話方塊</title>
</head>

<script language="javascript">
 /**
  * 這是檢查file欄位取得的實際檔名,確認是不是和text欄位(User看到的東西)一樣。
  * 這個method是除錯用的。
  */
 function showFileName()
 {
  alert(document.form1.file_up.value);
 }

 /**
  * 呼叫file欄位的click事件,IE限定,殘念~
  */
 function callFileSel()
 {
  document.form1.file_up.click();
 }

 /**
  * 在一般text欄位秀出選取的檔案名稱,這是給user看的。
  */
 function getValue()
 {
  document.form1.file_name.value=document.form1.file_up.value;
 }
</script>

<body>
<form name="form1" method="post" enctype="multipart/form-data" action="">
<div id="Layer1" style="position:absolute; z-index:1; visibility: hidden;">
 <input name="file_up" type="file" onChange="JavaScript:getValue()">
</div>
<table width="50%"  border="0" bgcolor="#CCCCCC">
  <tr>
    <td bgcolor="#EEEEEE"><div align="left">
      <table><tr><td>
      <input name="file_name" type="text" id="file_name" onFocus="JavaScript:this.blur()">
      </td>
      <td>
      <table  border="0" align="center" cellpadding="0" cellspacing="0">
       <tr>
        <td><img src="./img/button_l.gif"></td>
        <td nowrap background="./img/button_c.gif"><a href="JavaScript:callFileSel()">選取上傳檔案</a></td>
        <td><img src="./img/button_r.gif"></td>
       </tr>
      </table>
      </td></tr></table>
    </div></td>
  </tr>
  <tr>
    <td bgcolor="#EEEEEE"><div align="center">
      <input name="ok" type="button" id="ok" value="確定上傳此檔案" onClick="JavaScript:showFileName()">
    </div></td>
  </tr>
</table>
</form>
</body>
</html>

結果如圖:

各位做個更漂亮的按鈕吧~

參考資料:

「做個好看的HTML檔案上傳按鈕吧~_~」 有 6 則迴響

  1. I seldom discuss these articles, but I assumed this on deserved a thumb up

  2. Well I searched for the article title and found this,
    didn’t think i’d find the answer

  3. Awfully interesting piece of writing

  4. I seldom discuss these articles, but I thought this on deserved a well
    done

  5. I hardly ever discuss these articles, but I thought this on deserved a well
    done

發表留言