下面給大家分享下基於ajax實現檔案上傳並顯示進度條。在jsp部分,需要設計一個表單,form的屬性添加 enctype="multipart/form-data",設計一個iframe,作為隱藏。form的target等於iframe的name;
在servlet部分:檔案上傳用的Commons-FileupLoad,需要兩個Jar,commons-fileupload和commons-io,少了第二個會報出找不到類的異常;
第一個servlet處理上傳,及把上傳進度儲存到session,第二個servlet處理ajax請求,回傳session儲存的進度值;
進度條:可以用ajax拿到回傳的進度值,改變圖片的width實現變化;
jsp代碼:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!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=UTF-8"><title>Insert title here</title><link rel="stylesheet" type="text/css" href="css/progress.css"><script type="text/javascript" src="js/ul.js" charset="gbk"></script></head><body><form action="UploadServlet" name="f1" id="f1" method="post" enctype="multipart/form-data" target="if"> <input type="file" name="file1" /><br><br> <input type="reset" name="res1" value="重設"/> <input type="button" name="but1" value="提交" onclick="go();"/></form><br><div id="pro" class="pro" align="left"> <img alt="" src="photo/progress.png" width="0" height="15" id="imgpro"></div> <span id="prop" style="width:15px;height:15px;display: none;">0%</span><iframe id="if" name="if" src="" style="display: none"></iframe></body></html>
這是index.jsp裡的代碼:
提交後還在當前頁顯示進度,所以要用到iframe,提交後的返回放到隱藏的iframe裡,不影響頁面效果;
css代碼:
複製代碼 代碼如下:
.pro{
height:15px;
width:500px;
background: #FFFFF0;
border: 1px solid #8FBC8F;
margin: 0;
padding: 0;
display:none;
position: relative;
left:25px;
float:left;
}
js代碼
function go(){ f1.submit(); document.getElementById("pro").style.display="block"; document.getElementById("prop").style.display=""; timer=setInterval("getP()",50); }var xmlHttpRequest;function getP(){ if(window.XmlHttpRequest){ xmlHttpRequest=new XmlHttpRequest(); }else{ xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttpRequest.onreadystatechange=callBack; url="getProgressServlet"; xmlHttpRequest.open("post",url,true); xmlHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttpRequest.send("&timeStamp="+(new Date()).getTime()); }//回呼函數function callBack(){ if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200){ result=xmlHttpRequest.responseText; var result=result.replace(/(^\s*)|(\s*$)/g, ""); var res=result.split(","); var flag=res[1]; var per=parseInt(res[0]); var err=res[2]; document.getElementById("imgpro").style.width=per*5+"px"; document.getElementById("prop").innerHTML=per+"%"; if(flag=="OK"){ window.clearInterval(timer); alert("上傳成功!"); document.getElementById("pro").style.display="none"; document.getElementById("prop").innerHTML=""; f1.reset(); } if(err!=""||err.length>0){ window.clearInterval(timer); alert(err); } if(flag==null){ window.clearInterval(timer); } }}
flag為上傳成功標記,err為出錯標記;
servlet代碼(UploadServlet):
package com.ul.servlet;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.util.Iterator;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;public class UploadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設定編碼格式為utf-8 request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //擷取session,儲存進度和上傳結果,上傳結果初始值為NOK,當為Ok表示上傳完成 HttpSession session=request.getSession(); session.setAttribute("prog", "0"); session.setAttribute("result", "NOK"); session.setAttribute("error", ""); String error=""; //給上傳的檔案設一個最大值,這裡是不得超過50MB int maxSize=50*1024*1024; //建立工廠對象和檔案上傳對象 DiskFileItemFactory factory=new DiskFileItemFactory(); ServletFileUpload upload=new ServletFileUpload(factory); try { //解析上傳請求 List items=upload.parseRequest(request); Iterator itr=items.iterator(); while(itr.hasNext()){ FileItem item=(FileItem)itr.next(); //判斷是否為檔案域 if(!item.isFormField()){ if(item.getName()!=null&&!item.getName().equals("")){ //擷取上傳檔案大小和檔案名稱 long upFileSize=item.getSize(); String fileName=item.getName(); if(upFileSize>maxSize){ error="您上傳的檔案太大了,請選擇不超過50MB的檔案!"; break; } //此時檔案暫存在伺服器的記憶體中,構造臨時對象 File tempFile=new File(fileName); //指定檔案上傳伺服器的目錄及檔案名稱 File file=new File("f:\\temp",tempFile.getName()); //構造輸入資料流讀檔案 InputStream is=item.getInputStream(); int length=0; byte[] by=new byte[1024]; double persent=0; FileOutputStream fos=new FileOutputStream(file); PrintWriter out=response.getWriter(); while((length=is.read(by))!=-1){ //計算檔案進度 persent+=length/(double)upFileSize*100D; fos.write(by, 0, length); session.setAttribute("prog", Math.round(persent)+""); Thread.sleep(10); } fos.close(); Thread.sleep(1000); }else{ error="沒選擇上傳檔案!"; } } } } catch (Exception e) { e.printStackTrace(); error="上傳檔案出現錯誤:"+e.getMessage(); } if(!error.equals("")){ session.setAttribute("error", error); }else{ session.setAttribute("result", "OK"); } }}
不要忘記commons-io包
servlet代碼(getProgressServlet):
package com.ul.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class getProgressServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); HttpSession sesson=request.getSession(); PrintWriter out=response.getWriter(); String str=(String)sesson.getAttribute("prog")+""; String res=(String)sesson.getAttribute("result"); String err=(String)sesson.getAttribute("error"); System.out.println(str+","+res+","+err); out.print(str+","+res+","+err); out.flush(); out.close(); }}
效果圖如下:
以上就是本文的全部內容,希望對大家有所協助。