- 放個一般的檔案上傳物件,用css把它藏起來不讓使用者看到。
- 放個一般的文字輸入物件,用JavaScript設定為不可key in資料。
- 做個連結出來,看要用陽春的文字還是漂亮的圖案都可以。
- 當按下此連結時呼叫選取上傳檔案的對話方塊。
- 把取得的檔案名稱顯示在一般文字輸入物件。
範例程式碼如下:
<!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>
結果如圖:
各位做個更漂亮的按鈕吧~
參考資料:
- JavaWorld WebDesign板 http://www.javaworld.com.tw/jute/post/page?bid=34&sty=1&age=0&tpg=1
- QuirksMode http://www.quirksmode.org/home.shtml
發表留言