采用dwr ajax和struts開發文件上傳進度條

          編寫監聽器以及相關的類

          不用自己寫了,源碼可以從

          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上傳頁面示例代碼:

          <%@ page contentType="text/html; charset=gb2312" language="java"

          import="java.util.*" errorPage=""%>

          <%

          String path=request.getContextPath();

          %>

          <html locale="true">

          <head>

          <SCRIPT language=javascript>

           

          function check_file() {

           

          var strFileName=document.forms(0).file;

           

          if (strFileName.value==""){

          alert("請選擇要上傳的文件");

          return false;

          }

          startProgress();

          }

           

          function loadmessage(){

           

          <%

          if (request.getAttribute("message") != null) {

          %>

          window.alert("<%=request.getAttribute("message")%>");

          window.returnValue="yes";

           

          <%}%>

           

          }

           

          </SCRIPT>

          <title>上傳</title>

          <script src='<%=path%>/resources/js/upload.js'> </script>

           

          <script src='<%=path%>/dwr/interface/UploadMonitor.js'> </script>

           

          <script src='<%=path%>/dwr/engine.js'> </script>

          <script src='<%=path%>/dwr/util.js'> </script>

          <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onLoad="loadmessage()">

          <form name="form" method="post" action="<%=path%>/upload.do?method=upload" enctype="multipart/form-data" onSubmit="return check_file()">

          <table width="60%" border="0" cellspacing="1">

          <tr background-color=" #E7F5FE">

           

          <td width="30%" align="right">從文件導入:</td>

          <td width="51%"><input type="file" name="file" class="input"></td>

          <td width="27%"><input type="submit" name="files" class="button_4"

           

          style="border-style:None;width:71px;" value="確定" id="uploadbutton">

          </td>

          </tr>

           

          <tr align="left" background-color=" #E7F5FE">

           

           

          <td colspan="3">

          <div id="progressBar" style="display: none;">

           

          <div id="theMeter">

          <div id="progressBarText"></div>

          <div id="progressBarBox">

          <div id="progressBarBoxContent"></div>

           

          </div>

           

          </div>

          </div>

          </td>

           

          </tr>

           

          </table>

           

          </form>

          </body>

           

          </html>

          并且要修改一下\resources\js中的upload.js文件:

          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/下面

           

           

          <dwr>

           

          <allow>

          <create creator="new" javascript="UploadMonitor">

          <param name="class" value="be.telio.mediastore.ui.upload.UploadMonitor"/>

          </create>

          <convert converter="bean" match="be.telio.mediastore.ui.upload.UploadInfo"/>

          </allow>

           

          </dwr>

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

           

          <servlet>

          <servlet-name>dwr-invoker</servlet-name>

           

          <display-name>DWR Servlet</display-name>

           

           

          <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>

           

           

          <init-param>

          <param-name>debug</param-name>

           

          <param-value>false</param-value>

          </init-param>

           

          <init-param>

          <param-name>logLevel</param-name>

          <param-value>WARN</param-value>

          </init-param>

          </servlet>

           

          <servlet-mapping>

           

          <servlet-name>dwr-invoker</servlet-name> 

          <url-pattern>/dwr/*</url-pattern> 

          </servlet-mapping>

          編寫strutsMultipartRequestHandler :AjaxMultipartRequestHandler

          實現 MultipartRequestHandler接口并在struts-config.xml的controller中替換默認的multipartClass

          <controller>

          <set-property property="multipartClass"

          value="org.springside.components.ajaxupload.AjaxMultipartRequestHandler" />

           

           

          </controller>

          其實這個類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 < fname.length(); i ) {

           

          if (fname.charAt(i) == '.') {

           

          t = i;

          } }

           

           

          String filename = null;
          if (t > 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");

          }

          posted on 2008-10-24 14:00 deepbluesea 閱讀(1311) 評論(2)  編輯  收藏 所屬分類: JS

          評論

          # re: 采用dwr ajax和struts開發文件上傳進度條 2008-12-23 15:48 小東

          搞不明白 跟<controller>

          <set-property property="multipartClass"

          value="org.springside.components.ajaxupload.AjaxMultipartRequestHandler" />





          </controller> 里的春天傍邊也什么關系嗎

            回復  更多評論   

          # re: 采用dwr ajax和struts開發文件上傳進度條[未登錄] 2008-12-25 08:53 deepbluesea

          @小東
          沒明白  回復  更多評論   

          <2008年10月>
          2829301234
          567891011
          12131415161718
          19202122232425
          2627282930311
          2345678

          導航

          統計

          公告

          MSN:zzlljj8833@hotmail.com lava:5832911

          常用鏈接

          留言簿(1)

          隨筆分類(9)

          隨筆檔案(18)

          文章分類(1)

          文章檔案(1)

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 原平市| 惠州市| 顺平县| 鹿邑县| 吉安市| 抚州市| 南宁市| 商河县| 高唐县| 惠来县| 娄底市| 东乌| 阳春市| 都兰县| 固安县| 右玉县| 出国| 青海省| 太白县| 丹巴县| 三穗县| 黑山县| 邵阳县| 昌平区| 武功县| 丰县| 宜君县| 平和县| 安徽省| 七台河市| 太白县| 洪江市| 乌兰县| 石柱| 惠水县| SHOW| 读书| 阿荣旗| 沛县| 滨海县| 尚志市|