這個內容,是我在看到iteye的論壇裏面看到的,特地弄個過來保存一下,原博客地址是:
[url]http://www.iteye.com/topic/81120[/url]
首先要說的就是 ajax 是無法實現上傳文件的,可以想一下ajax與後臺通信都是通過傳遞字符串,怎麼能傳遞文件呢?其實出於安全考慮js是不能操作文件的,所以就不要再說用ajax來實現文件的上傳了,這是不可能的。
而本文實現的文件上傳也是無頁面刷新的,可以說是一種"類似AJAX"方法。
ps:Ajax技術基本上可以說是由google公司帶起來的,但少Gmail中上傳文件用的還是 IFrame,所以說使用IFrame來上傳文件是最好的選擇。
我在這裏這裏用的技術是jsp,其實asp,php等也是一樣可以這麼實現的
一共兩個文件就可實現:index.html 和 upload.jsp,在這裏講解一下,文後會附上源碼
index.jsp頁面:
<script type="text/javascript">
function callback(msg)
{
document.getElementById("file").outerHTML = document.getElementById("file").outerHTML;
document.getElementById("msg").innerHTML = "<font color=red>"+msg+"</font>";
}
</script>
<body>
<form action="upload.jsp" id="form1" name="form1" encType="multipart/form-data" method="post" target="hidden_frame" >
<input type="file" id="file" name="file" style="width:450">
<INPUT type="submit" value="上傳文件"><span id="msg"></span>
<br>
<font color="red">支持JPG,JPEG,GIF,BMP,SWF,RMVB,RM,AVI,EXE文件的上傳</font>
<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
</form>
</body>
upload.jsp頁面:
<%@ page import="com.jspsmart.upload.SmartUpload" %>
<%
//新建一個SmartUpload對象
SmartUpload su = new SmartUpload();
//上傳初始化
su.initialize(pageContext);
// 設定上傳限制
//1.限制每個上傳文件的最大長度。
su.setMaxFileSize(10000000);
//2.限制總上傳數據的長度。
su.setTotalMaxFileSize(20000000);
//3.設定允許上傳的文件(通過擴展名限制),僅允許doc,txt文件。
su.setAllowedFilesList("doc,txt,jpg,rar,mid,waw,mp3,gif,exe");
boolean sign = true;
//4.設定禁止上傳的文件(通過擴展名限制),禁止上傳帶有exe,bat,jsp,htm,html擴展名的文件和沒有擴展名的文件。
try {
su.setDeniedFilesList("bat,jsp,htm,html");
//上傳文件
su.upload();
//將上傳文件保存到指定目錄
su.save("/upfile");
} catch (Exception e) {
e.printStackTrace();
sign = false;
}
if(sign==true)
{
out.println("<script>parent.callback('文件上傳成功')</script>");
}else
{
out.println("<script>parent.callback('文件上傳失敗')</script>");
}
%>
此外,還需要用到jspSmartUpload.jar包