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

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

          Posted on 2007-05-01 21:04 ZelluX 閱讀(465) 評論(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

          主站蜘蛛池模板: 莱芜市| 南华县| 曲水县| 仪征市| 平南县| 桃园市| 嘉义县| 通榆县| 洮南市| 偏关县| 金华市| 乌兰察布市| 都昌县| 阳原县| 太白县| 枣庄市| 满城县| 临沭县| 玛纳斯县| 平度市| 和平区| 定陶县| 天峨县| 托里县| 伊金霍洛旗| 迁西县| 鄂托克旗| 惠安县| 自贡市| 青川县| 钦州市| 舞钢市| 信丰县| 霍山县| 铅山县| 高邑县| 民丰县| 遵义县| 永吉县| 大荔县| 永安市|