免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3634 | 回复: 0
打印 上一主题 下一主题

struts2进度条(一) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-01-13 21:04 |只看该作者 |倒序浏览
编写监听器以及相关的类
不用自己写了,源码可以从
http://www.telio.be/blog/2006/01/06/ajax-upload-progress-monitor-for-commons-fileupload-example里面下载,
下载地址
http://www.telio.be/blog/wp-content/uploads/2006/01/ajax-upload-1.0.war
下载完之后,你需要解包,在命令行中:
jar xvf ajax-upload-1.0.war
源码就在\WEB-INF\src下面
将要用到的文件有resources文件夹下,\WEB-INF\下面的dwr.xml和lib下面的jar文件
上传页面
在上面解开的包里面有index.jsp这个是上传页面,upload.jsp负责上传,resources包里面包含了dwr与服务器通讯的javascript脚本,你需要把index.jsp的form中的action换成你的struts action即可,然后把form中的file名改成你actionform中的file属性名,把页面中剩余的file去掉
index.jsp上传页面示例代码:





function check_file() {
  var strFileName=document.forms(0).file;
  if (strFileName.value==""){
    alert("请选择要上传的文件");
    return false;
  }
  startProgress();
}
function loadmessage(){
         
           window.alert("");
           window.returnValue="yes";
        
}

上传
       /resources/js/upload.js'>  
        /dwr/interface/UploadMonitor.js'>  
        /dwr/engine.js'>  
        /dwr/util.js'>  
         
            #progressBar { padding-top: 5px; }
            #progressBarBox { width: 350px; height: 20px; border: 1px inset; background: #eee;}
            #progressBarBoxContent { width: 0; height: 20px; border-right: 1px solid #444; background: blue; }
         
       /css/style.css" type="text/css" rel="stylesheet">






/upload.do?method=upload" enctype="multipart/form-data"  onSubmit="return check_file()">
   
     
      从文件导入:
      
      
      
     
     
      
      
            
                 
                 
                     
                 
            
         
      
     
   



并且要修改一下\resources\js中的upload.js文件:
/* Licence:
*   Use this however/wherever you like, just don't blame me if it breaks anything.
*
* Credit:
*   If you're nice, you'll leave this bit:
*
*   Class by Pierre-Alexandre Losson -- http://www.telio.be/blog
*   email : plosson@users.sourceforge.net
*/
function refreshProgress()
{
    UploadMonitor.getUploadInfo(updateProgress);
}
function updateProgress(uploadInfo)
{
    if (uploadInfo.inProgress)
    {
       document.getElementById('uploadbutton').disabled = true;
        document.getElementById('file').disabled = true;
        var fileIndex = uploadInfo.fileIndex;
        var progressPercent = Math.ceil((uploadInfo.bytesRead / uploadInfo.totalSize) * 100);
        document.getElementById('progressBarText').innerHTML = '文件读取进度: ' + progressPercent + '%';
        document.getElementById('progressBarBoxContent').style.width = parseInt(progressPercent * 3.5) + 'px';
        window.setTimeout('refreshProgress()', 1000);
    }
    else
    {
        document.getElementById('uploadbutton').disabled = false;
        document.getElementById('file').disabled = false;
    }
    return true;
}
function startProgress()
{
    document.getElementById('progressBar').style.display = 'block';
    document.getElementById('progressBarText').innerHTML = '文件读取进度: 0%';
    document.getElementById('uploadbutton').disabled = true;
    // wait a little while to make sure the upload has started ..
    window.setTimeout("refreshProgress()", 1000);
    return true;
}
配置dwr.xml
放在/WEB-INF/下面

     
         
            
         
         
     

web.xml中配置dwr,省略spring,struts等的配置

              dwr-invoker
              DWR Servlet
              uk.ltd.getahead.dwr.DWRServlet
               
                     debug
                     false
               
               
                     logLevel
                     WARN
               


              dwr-invoker
              /dwr/*

编写struts的MultipartRequestHandler :AjaxMultipartRequestHandler
实现 MultipartRequestHandler接口并在struts-config.xml的controller中替换默认的multipartClass

               

其实这个类AjaxMultipartRequestHandler编写很简单,把struts的src源码中的org.apache.struts.upload.CommonsMultipartRequestHandler.java修改一下就可以了:
在public void handleRequest(HttpServletRequest request)
           throws ServletException {
方法中把定义factory之前的那几行代码注释掉然后写入
UploadListener listener = new UploadListener(request, 30);
FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
之后再注释掉
// upload.setSizeThreshold((int) getSizeThreshold(ac));
// upload.setRepositoryPath(getRepositoryPath(ac));
这个类就算写完了
编写struts上传类
就用你原来编写的struts上传类
上传方法代码段示例:
/**
     * 上传文件
     */
    public ActionForward upload(ActionMapping mapping, ActionForm form,
           HttpServletRequest request, HttpServletResponse response)
           throws Exception {
       String path = getServlet().getServletContext().getRealPath("/");
       log.info(">>>>>>>>>>>>>>>path:" + path);
       if (form == null) {
           return mapping.findForward("success");
       }
       FileUploadForm fuf = (FileUploadForm) form;
       FormFile file = fuf.getFile();
       try {
           if (file == null) {
              log.info(">>>>>>>>>>>>>>>file为空");
              return mapping.findForward("success");
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       String fname = file.getFileName();
       int t = 0;
       for (int i = 0; i  0) {
           filename = fname.substring(0, t);
       }
       log.info(">>>>>>>>>>>>>>>文件名:" + filename);
       String filepath = path + "dataimport/upfiles/" + fname;
       File f = new File(path + "dataimport/upfiles/");
       log.info(">>>>>>>>>>>>>>>文件生成路径:" + filepath);
       if (!f.exists()) {
           f.mkdirs();
       } else {
           log.info(">>>>>>>>>>>>>>>路径存在");
       }
       InputStream stream = file.getInputStream();
       OutputStream os = new FileOutputStream(path + "dataimport/upfiles/"
              + fname);
       int readBytes = 0;
       byte buffer[] = new byte[8192];
       while ((readBytes = stream.read(buffer, 0, 8192)) != -1) {
           os.write(buffer, 0, readBytes);
       }
       os.close();
       stream.close();
       file.destroy();
      
       String message = "成功!";
       request.setAttribute("message", message);
       return mapping.findForward("success");
    }

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/110188/showart_2148083.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP