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

          主站蜘蛛池模板: 灵寿县| 浦县| 夏河县| 鹰潭市| 密云县| 贵州省| 吉水县| 阿拉尔市| 禹城市| 特克斯县| 鞍山市| 乌鲁木齐县| 武鸣县| 峨边| 北川| 化隆| 海宁市| 龙门县| 上蔡县| 阜康市| 来凤县| 登封市| 怀宁县| 安徽省| 太谷县| 巴里| 墨玉县| 崇信县| 汶上县| 磐安县| 柞水县| 柘荣县| 九龙城区| 鄂州市| 宕昌县| 乌鲁木齐县| 民权县| 娱乐| 淳安县| 富顺县| 汨罗市|