<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    eric-1001c

      BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
      3 隨筆 :: 45 文章 :: 12 評論 :: 0 Trackbacks

    在god老大的激勵之下,我開始著手做這個上傳下載了,由于它只是個作業,所以我能做的就是完成它,完美和時間的權衡下,時間最重要,我花了一個星期使用不熟練的struts來寫程序,對于struts的精神理解已經很透徹了,只是struts標簽庫里的東西,各種form還沒有完全熟悉,呵呵,反正god老大的東西不要struts開發,這也為程序留下缺陷埋下伏筆。下面列出我的代碼:

    上傳:

    selfile.jsp

    <%@ page language="java"%>
    <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
    <html:html>
    <html:form action="/upload.do" enctype="multipart/form-data">
    <html:file property="theFile"/>
    <html:submit/>
    </html:form>
    </html:html>

    ------------------------------------------------------------------------------------

    UploadForm.java

    package com.vv.struts.form;

    import javax.servlet.http.HttpServletRequest;
    import org.apache.struts.action.*;
    import org.apache.struts.upload.*;

    /**
    * <p>Title:UpLoadForm</p>
    * <p>Description: QRRSMMS </p>
    * <p>Copyright: Copyright (c) 2004 jiahansoft</p>
    * <p>Company: jiahansoft</p>
    * @author wanghw
    * @version 1.0
    */

    public class UploadForm extends ActionForm {

     public static final String ERROR_PROPERTY_MAX_LENGTH_EXCEEDED = "org.apache.struts.webapp.upload.MaxLengthExceeded";

     protected FormFile theFile;
     public FormFile getTheFile() {
      return theFile;
     }
     public void setTheFile(FormFile theFile) {
      this.theFile = theFile;
     }
     public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
     {
      ActionErrors errors = null;
      //has the maximum length been exceeded?
      Boolean maxLengthExceeded = (Boolean)
      request.getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
      if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue()))
      {
       errors = new ActionErrors();
       errors.add(ERROR_PROPERTY_MAX_LENGTH_EXCEEDED, new ActionError("maxLengthExceeded"));
      }
      return errors;

     }
    }

    -------------------------------------------------------------------------------------

    UploadAction.java

    package com.vv.struts.action;

    import java.io.*;
    import javax.servlet.http.*;
    import org.apache.struts.action.*;
    import org.apache.struts.upload.FormFile;
    import com.vv.struts.form.UploadForm;

    /**
    * <p>Title:UpLoadAction</p>
    * <p>Description: QRRSMMS </p>
    * <p>Copyright: Copyright (c) 2004 jiahansoft</p>
    * <p>Company: jiahansoft</p>
    * @author wanghw
    * @version 1.0
    */

    public class UploadAction extends Action {
     
    public ActionForward execute(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws Exception {
     if(form==null) System.out.println("null");
     if (form instanceof UploadForm) {//如果form是uploadsForm
      String encoding = request.getCharacterEncoding();
      if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8")))
      {
       response.setContentType("text/html; charset=gb2312");//如果沒有指定編碼,編碼格式為gb2312
      }
      UploadForm theForm = (UploadForm ) form;
      FormFile file = theForm.getTheFile();//取得上傳的文件
      try {
       InputStream stream = file.getInputStream();//把文件讀入
       String filePath = request.getRealPath("/");//取當前系統路徑
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       OutputStream bos = new FileOutputStream(filePath + "/file/" +
         file.getFileName());//建立一個上傳文件的輸出流
       //System.out.println(filePath+"/"+file.getFileName());
       int bytesRead = 0;
       byte[] buffer = new byte[8192];
       while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1) {
        bos.write(buffer, 0, bytesRead);//將文件寫入服務器
       }
       bos.close();
       stream.close();
      }catch(Exception e){
       System.err.print(e);
      }
      //request.setAttribute("dat",file.getFileName());
      return mapping.findForward("success");
     }
     return null;
    }
    }
    其它的都是幾個次要的頁面,老實這部分基本上就是我抄的,雖然我也能寫,但是他確實比我寫的好,特別是對struts的字段的使用,這些都是我不知道的,我做的只是修改成我要的程序,唯一不好的就是它使用request.getRealPath("/"),這個方法很危險,可是一時間我沒有找到更好的方法代替它,這些是可以避免的,為什么使用它和后面的下載有關系,呵呵。

    下載:

    test.jsp


    <%@ page language="java"%>

    <a href="/other/download.do">here</a>

    ---------------------------------------------------------------------------

    download.jsp


    <%@ page language="java" contentType="text/html;charset=UTF-8"%>

    <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
    <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
    <%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %>
    <%@ taglib uri="http://jakarta.apache.org/struts/tags-tiles" prefix="tiles" %>
    <%@ taglib uri="http://jakarta.apache.org/struts/tags-template" prefix="template" %>
    <%@ taglib uri="http://jakarta.apache.org/struts/tags-nested" prefix="nested" %>

    <html xmlns:o="urn:schemas-microsoft-com:office:office"
    xmlns:w="urn:schemas-microsoft-com:office:word"
    xmlns="http://www.w3.org/TR/REC-html40">

    <head>
    <style>
    </style>
    </head>
    <body>

     <bean:write name="DownWordForm" property="name" />
     <logic:notEmpty name="list" >
      <logic:iterate id="row" name="list">
       <p><html:link page="/loaded.do" paramId="name" paramName="row">
       <bean:write name="row"/>
       </html:link>
       </p>
      </logic:iterate>
      </logic:notEmpty>
    </body>

    </html>

    對于struts的標簽一直不是很理解,在做這個的時候受了不少的苦呀,原來iterate里的row可以作為html:link的屬性值,我一直都不知道怎么來動態生成需要的鏈接,看了好多的例子,甚至在action里要輸出到jsp的字符串上再加入字符串“<html:link.......>”,然后用<bean:write>來輸出,可惜struts似乎使用了回壓字符流的,這個方案失敗了,看了動態生成復選框的例子后明白了,修改了后就能用了,中間有個小插曲,我把paramName改為list,然后把<bean:write name="list">,結果把list里的所有值作為一個單獨的鏈接重復list.size()次輸出,而不是把list的每個值重復輸出list.size()次,原理其實很簡單,只是感嘆struts的作者寫這個好像廢了不少的心呀。

    DownloadAction.java

    package com.vv.struts.action;

    import org.apache.struts.action.*;
    import javax.servlet.http.*;

    import java.io.File;
    import java.util.*;
    /**
     * <p>Title:DownloadWordAction </p>
     * <p>Description: QRRSMMS </p>
     * <p>Copyright: Copyright (c) 2004 jiahansoft</p>
     * <p>Company: jiahansoft</p>
     * @author wanghw
     * @version 1.0
     */

    public class DownloadAction extends Action {
     
     File myDir;
     File[] contents;

      public ActionForward execute(ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response)
          throws Exception {
        DynaActionForm testForm = (DynaActionForm)form;
        testForm.set("name","a test word");
       
        ArrayList list = new ArrayList();
        String path=request.getRealPath("/")+"file";
        String FullPath;
       System.out.println(path);
     myDir=new File(path);
     list.clear();
     contents=myDir.listFiles();
     //HashMap row = new HashMap();
     //System.out.println(contents.length);
     for(int i=0;i<contents.length;i++){
      FullPath=contents[i].getName();
      //row.put("1",FullPath);
      list.add(FullPath);
      System.out.println(FullPath);
     }
        request.setAttribute("list",list);
       
        return mapping.findForward("display");
    }
    }

    又用了限制級的方法,我也不想的我已用相對路徑它就報錯,我必須承認,這個寫的不夠標準,應該用資源文件存儲文件路徑,而不是反復列舉,為什么我不用呢?我當時忘了可以用資源文件了。。。。。。。

    LoadedForm.java

    package com.vv.struts.form;

    import org.apache.struts.action.ActionForm;

    /**
     * MyEclipse Struts
     * Creation date: 05-18-2006
     *
     * XDoclet definition:
     * @struts:form name="loadedForm"
     */
    public class LoadedForm extends ActionForm {

     // --------------------------------------------------------- Instance Variables

     /** name property */
     private String name;

     /**
      * Returns the name.
      * @return String
      */
     public String getName() {
      return name;
     }

     /**
      * Set the name.
      * @param name The name to set
      */
     public void setName(String name) {
      this.name = name;
     }

    }

    ---------------------------------------------------------------------------------

    LoadedAction.java

    package com.vv.struts.action;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;

    import java.io.*;
    import com.vv.struts.form.LoadedForm;
    /**
     * MyEclipse Struts
     * Creation date: 05-17-2006
     *
     * XDoclet definition:
     * @struts:action validate="true"
     */
    public class LoadedAction extends Action {

     // --------------------------------------------------------- Instance Variables

     // --------------------------------------------------------- Methods

     /**
      * Method execute
      * @param mapping
      * @param form
      * @param request
      * @param response
      * @return ActionForward
      */
     public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) throws Exception{
     
      LoadedForm doc=(LoadedForm)form;
      //if(form==null) System.out.println("null");
      String docName = doc.getName();
      File f;
      if(docName!=""){
      String docFullPath=request.getRealPath("/");
      //System.out.println(docFullPath);
     
      String Name = docName.substring(0,docName.lastIndexOf("."));
            String prefix = docName.substring(docName.lastIndexOf("."));
            //byte[] dn=Name.getBytes("UTF-8");
            //Name =new String(dn,"ISO-8859-1");
          //Name=java.net.URLEncoder.encode(Name,"GBK");
            docName = Name +prefix;
         
          System.out.println();
          System.out.println(docName);
        
          f = new File(docFullPath+"file\\"+docName);
         if (!f.exists())
         {
                return (mapping.findForward("nofile"));
         }
        
         BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
         byte[] buf = new byte[1024];
         int len = 0;
         response.reset();       
        
        
         response.setContentType("application/x-msdownload;charset=UTF-8");
         response.setHeader("Content-Disposition", "attachment; filename=" +docName);


          OutputStream out = response.getOutputStream();
          while((len = br.read(buf)) >0)
          out.write(buf,0,len);
          br.close();
          out.close();
          return mapping.findForward("download");
     }
      return mapping.findForward("nofile");
     }
     }

    我還是不幸運的遇見中文亂碼問題,如果下載的是中文文件的話,那么name的值就是亂碼,雖然我用了轉換字符的代碼,可惜事實上它沒有用,在:http://www.mx68.com/WebDeveloper/Print.asp?ArticleID=41762&Page=1中的三個方法我都使用了,可是都沒什么太大的變化,只是顯示不同的亂碼而已,郁悶。實在不行了,只能把這篇不怎么樣的作業上交god了。作為個程序員來說,它應該是追求完美的,但是我認為效率和時間是個凸函數,并不是但方面的極致就是最好,兩者的最佳切合點才是最好。

    posted on 2008-03-12 23:08 Eric-1001c 閱讀(141) 評論(0)  編輯  收藏

    只有注冊用戶登錄后才能發表評論。


    網站導航:
     
    主站蜘蛛池模板: 亚洲真人无码永久在线| 免费日本黄色网址| 亚洲AV无码一区二区二三区软件| 精品久久久久久亚洲综合网| 久久久久国色AV免费观看性色 | 国产亚洲精品一品区99热| 乱爱性全过程免费视频| 亚洲AV无码一区二三区 | 亚洲日本VA午夜在线影院| 午夜宅男在线永久免费观看网| 亚洲ts人妖网站| 日韩免费毛片视频| 免费观看亚洲人成网站| 亚洲毛片网址在线观看中文字幕| 无遮挡国产高潮视频免费观看| 亚洲精品第一国产综合境外资源 | 久久香蕉国产线看免费| 78成人精品电影在线播放日韩精品电影一区亚洲 | 国产无遮挡色视频免费观看性色| 久久亚洲欧洲国产综合| 久久久久免费视频| 亚洲综合一区二区精品导航| 无码少妇精品一区二区免费动态| 亚洲免费视频播放| 国产成人免费网站在线观看| 国产精品无码一区二区三区免费 | 免费国产怡红院在线观看| 一级美国片免费看| 亚洲人成网www| 成人午夜视频免费| 亚洲国产精品线观看不卡| 成人免费毛片观看| 一二三区免费视频| 亚洲综合综合在线| 日本久久久免费高清| 精品一区二区三区免费观看| 亚洲免费观看网站| 国产亚洲AV手机在线观看| 69pao强力打造免费高清| 亚洲av成本人无码网站| 国产亚洲一区二区三区在线观看 |