posts - 403, comments - 310, trackbacks - 0, articles - 7
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          Struts 學習筆記(3) - 文件上傳的實現

          Posted on 2007-05-01 21:04 ZelluX 閱讀(470) 評論(0)  編輯  收藏 所屬分類: OOP
          struts標簽庫中有相應html:file標簽,enctype這個屬性貌似去掉也可以,不知道有什么用。
          1<html:form action="/upload" enctype="multipart/form-data">
          2theFile : 
          3<html:file property="theFile" />
          4<html:errors property="theFile"/><br/>
          5<html:submit/>
          6</html:form>
          網上看到的例子是在Action類中處理的,不知道這么做合不合理,這個是簡單的處理代碼,沒有驗證文件大小和同名文件是否存在,注意先要在相應目錄中建立file目錄。
           1UploadForm uploadForm = (UploadForm) form;// TODO Auto-generated method stub
           2FormFile file = uploadForm.getTheFile();
           3try {
           4  InputStream stream = file.getInputStream();
           5  String filePath = getServlet().getServletContext().getRealPath("/");
           6  OutputStream fileout = new FileOutputStream(filePath + "/file/" + file.getFileName());
           7  int bytesRead = 0;
           8  byte[] buffer = new byte[8192];
           9  while ((bytesRead = stream.read(buffer, 08192)) != -1{
          10    fileout.write(buffer, 0, bytesRead);
          11  }

          12  fileout.close();
          13  stream.close();
          14}
           catch (Exception e) {
          15  System.err.println(e);
          16}

          一點積累:
          1. Action類代碼中要獲得當前地址可以使用
          getServlet().getServletContext().getRealPath(String)

          2. Forward的目標地址前面貌似都要加"/"。 Path success.jsp does not start with a "/" character

          主站蜘蛛池模板: 建始县| 平遥县| 辽阳县| 体育| 民勤县| 基隆市| 称多县| 平武县| 邹城市| 新绛县| 扶沟县| 昂仁县| 牡丹江市| 镇坪县| 溧阳市| 湘潭县| 师宗县| 台前县| 宝清县| 松江区| 东阳市| 元氏县| 永济市| 崇文区| 监利县| 泗洪县| 承德市| 丽江市| 三明市| 崇文区| 景德镇市| 古田县| 平乡县| 巴东县| 吴忠市| 汤原县| 甘谷县| 图片| 舒城县| 沅江市| 凤山县|