色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

利用jsp+Extjs實(shí)現(xiàn)動(dòng)態(tài)顯示文件上傳進(jìn)度

需求來(lái)源是這樣的:上傳一個(gè)很大的excel文件到server, server會(huì)解析這個(gè)excel, 然后一條一條的插入到數(shù)據(jù)庫(kù),整個(gè)過(guò)程要耗費(fèi)很長(zhǎng)時(shí)間,因此當(dāng)用戶點(diǎn)擊上傳之后,需要顯示一個(gè)進(jìn)度條,并且能夠根據(jù)后臺(tái)的接收的數(shù)據(jù)量和處理的進(jìn)度及時(shí)更新進(jìn)度條。

分析:后臺(tái)需要兩個(gè)組件,uploadController.jsp用來(lái)接收并且處理數(shù)據(jù),它會(huì)動(dòng)態(tài)的把進(jìn)度信息放到session,另一個(gè)組件processController.jsp用來(lái)更新進(jìn)度條;當(dāng)用戶點(diǎn)“上傳”之后,form被提交給uploadController.jsp,同時(shí)用js啟動(dòng)一個(gè)ajax請(qǐng)求到processController.jsp,ajax用獲得的進(jìn)度百分比更新進(jìn)度條的顯示進(jìn)度,而且這個(gè)過(guò)程每秒重復(fù)一次;這就是本例的基本工作原理。

現(xiàn)在的問題是server接收數(shù)據(jù)的時(shí)候怎么知道接收的數(shù)據(jù)占總數(shù)據(jù)的多少? 如果我們從頭自己寫一個(gè)文件上傳組件,那這個(gè)問題很好解決,關(guān)鍵是很多時(shí)候我們都是用的成熟的組件,比如apache commons fileupload; 比較幸運(yùn)的是,apache早就想到了這個(gè)問題,所以預(yù)留了接口可以用來(lái)獲取接收數(shù)據(jù)的百分比;因此我就用apache commons fileupload來(lái)接收上傳文件。

uploadController.jsp:
復(fù)制代碼 代碼如下:
<%@ page language="Java" import="Java.util.*, Java.io.*, org.apache.commons.fileupload.*, org.apache.commons.fileupload.disk.DiskFileItemFactory, org.apache.commons.fileupload.servlet.ServletFileUpload" pageEncoding="utf-8"%>
<%
//注意上面的import的jar包是必須的
//下面是使用apache commons fileupload接收上傳文件;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//因?yàn)閮?nèi)部類無(wú)法引用request,所以要實(shí)現(xiàn)一個(gè)。
class MyProgressListener implements ProgressListener{
 private HttpServletRequest request = null;
 MyProgressListener(HttpServletRequest request){
  this.request = request;
 }
 public void update(long pBytesRead, long pContentLength, int pItems) {
  double percentage = ((double)pBytesRead/(double)pContentLength);
  //上傳的進(jìn)度保存到session,以便processController.jsp使用
  request.getSession().setAttribute("uploadPercentage", percentage);
 }
}
upload.setProgressListener(new MyProgressListener(request));
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField()){

    } else {
        //String fieldName = item.getFieldName();
        String fileName = item.getName();
        //String contentType = item.getContentType();
       System.out.println();
        boolean isInMemory = item.isInMemory();
        long sizeInBytes = item.getSize();
        File uploadedFile = new File("c://" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf(".")));
        item.write(uploadedFile);
    }
}
out.write("{success:true,msg:'保存上傳文件數(shù)據(jù)并分析Excel成功!'}");
out.flush();
%>

processController.jsp:
復(fù)制代碼 代碼如下:
<%@ page language="Java" import="Java.util.*" contentType = "text/html;charset=UTF-8" pageEncoding="utf-8"%>
<%
 //注意上面的抬頭是必須的。否則會(huì)有ajax亂碼問題。
 //從session取出uploadPercentage并送回瀏覽器
 Object percent = request.getSession().getAttribute("uploadPercentage");
 String msg = "";
 double d = 0;
 if(percent==null){
  d = 0;
 }
 else{
  d = (Double)percent;
  //System.out.println("+++++++processController: " + d);
 }
 if(d<1){
 //d<1代表正在上傳,
  msg = "正在上傳文件...";
  out.write("{success:true, msg: '"+msg+"', percentage:'" + d + "', finished: false}");
 }
 else if(d>=1){
  //d>1 代表上傳已經(jīng)結(jié)束,開始處理分析excel,
  //本例只是模擬處理excel,在session中放置一個(gè)processExcelPercentage,代表分析excel的進(jìn)度。
  msg = "正在分析處理Excel...";
  String finished = "false";
  double processExcelPercentage = 0.0;
  Object o = request.getSession().getAttribute("processExcelPercentage");
  if(o==null){
   processExcelPercentage = 0.0;
   request.getSession().setAttribute("processExcelPercentage", 0.0);

  }
  else{
   //模擬處理excel,百分比每次遞增0.1
   processExcelPercentage = (Double)o + 0.1;
   request.getSession().setAttribute("processExcelPercentage", processExcelPercentage);
   if(processExcelPercentage>=1){
    //當(dāng)processExcelPercentage>1代表excel分析完畢。
    request.getSession().removeAttribute("uploadPercentage");
    request.getSession().removeAttribute("processExcelPercentage");
    //客戶端判斷是否結(jié)束的標(biāo)志
    finished = "true";
   }
  }
  out.write("{success:true, msg: '"+msg+"', percentage:'" + processExcelPercentage + "', finished: "+ finished +"}");
  //注意返回的數(shù)據(jù),success代表狀態(tài)
  //percentage是百分比
  //finished代表整個(gè)過(guò)程是否結(jié)束。
 }
 out.flush();
%>

表單頁(yè)面upload.html:
復(fù)制代碼 代碼如下:
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>File Upload Field Example</title>
  <link rel="stylesheet" type="text/css"
   href="ext/resources/css/ext-all.css" />
  <script type="text/Javascript" src="ext/adapter/ext/ext-base.js"> </script>
  <script type="text/Javascript" src="ext/ext-all.js"> </script>
  <style>
</style>
 </head>
 <body>
  <a href="http://blog.csdn.NET/sunxing007">sunxing007</a>
  <div id="form"></div>
 </body>
 <script>
var fm = new Ext.FormPanel({
 title: '上傳excel文件',
 url:'uploadController.jsp?t=' + new Date(),
 autoScroll:true,
 applyTo: 'form',
 height: 120,
 width: 500,
 frame:false,
 fileUpload: true,
 defaultType:'textfield',
 labelWidth:200,
 items:[{
  xtype:'field',
  fieldLabel:'請(qǐng)選擇要上傳的Excel文件 ',
  allowBlank:false,
  inputType:'file',
  name:'file'
 }],
 buttons: [{
  text: '開始上傳',
  handler: function(){
   //點(diǎn)擊'開始上傳'之后,將由這個(gè)function來(lái)處理。
      if(fm.form.isValid()){//驗(yàn)證form, 本例略掉了
      //顯示進(jìn)度條
    Ext.MessageBox.show({
        title: '正在上傳文件',
        //msg: 'Processing...',
        width:240,
        progress:true,
        closable:false,
        buttons:{cancel:'Cancel'}
    });
    //form提交
        fm.getForm().submit();
        //設(shè)置一個(gè)定時(shí)器,每500毫秒向processController發(fā)送一次ajax請(qǐng)求
      var i = 0;
      var timer = setInterval(function(){
        //請(qǐng)求事例
         Ext.Ajax.request({
         //下面的url的寫法很關(guān)鍵,我為了這個(gè)調(diào)試了好半天
         //以后凡是在ajax的請(qǐng)求的url上面都要帶上日期戳,
         //否則極有可能每次出現(xiàn)的數(shù)據(jù)都是一樣的,
         //這和瀏覽器緩存有關(guān)
      url: 'processController.jsp?t=' + new Date(),
      method: 'get',
      //處理ajax的返回?cái)?shù)據(jù)
      success: function(response, options){
       status = response.responseText + " " + i++;
       var obj = Ext.util.JSON.decode(response.responseText);
       if(obj.success!=false){
        if(obj.finished){
         clearInterval(timer); 
         //status = response.responseText;
         Ext.MessageBox.updateProgress(1, 'finished', 'finished');
         Ext.MessageBox.hide();
        }
        else{
         Ext.MessageBox.updateProgress(obj.percentage, obj.msg); 
        }
       }
      },
      failure: function(){
       clearInterval(timer);
       Ext.Msg.alert('錯(cuò)誤', '發(fā)生錯(cuò)誤了。');
      }
     });
      }, 500);

      }
      else{
       Ext.Msg.alert("消息","請(qǐng)先選擇Excel文件再上傳.");
      }
  }
 }]
});
</script>
</html>

把這三個(gè)文件放到tomcat/webapps/ROOT/, 同時(shí)把ext的主要文件也放到這里,啟動(dòng)tomcat即可測(cè)試:http://localhost:8080/upload.html

我的資源里面有完整的示例文件:點(diǎn)擊下載, 下載zip文件之后解壓到tomcat/webapps/ROOT/即可測(cè)試。

最后需要特別提醒,因?yàn)橛玫搅薬pache 的fileUpload組件,因此,需要把common-fileupload.jar放到ROOT/WEB-INF/lib下。
 

jsp技術(shù)利用jsp+Extjs實(shí)現(xiàn)動(dòng)態(tài)顯示文件上傳進(jìn)度,轉(zhuǎn)載需保留來(lái)源!

鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。

主站蜘蛛池模板: 张家界市| 西盟| 吐鲁番市| 宜丰县| 梅河口市| 伊金霍洛旗| 深水埗区| 二连浩特市| 菏泽市| 武夷山市| 兴山县| 长海县| 林甸县| 米林县| 辉县市| 临漳县| 光泽县| 洛扎县| 托克托县| 怀柔区| 福州市| 伊春市| 孝昌县| 英山县| 广水市| 太康县| 诸城市| 孟州市| 土默特左旗| 岳池县| 贺州市| 平昌县| 和龙市| 原平市| 广安市| 门源| 黄石市| 楚雄市| 巩义市| 呼伦贝尔市| 定结县|