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

          主站蜘蛛池模板: 宾阳县| 郎溪县| 林口县| 手机| 内乡县| 原阳县| 武义县| 陵川县| 米林县| 拉萨市| 内乡县| 福贡县| 昌江| 惠州市| 额尔古纳市| 慈利县| 沧州市| 桃源县| 东平县| 闵行区| 临漳县| 任丘市| 石楼县| 报价| 六枝特区| 靖西县| 仪征市| 珲春市| 温州市| 怀柔区| 临澧县| 苍南县| 仁布县| 禄丰县| 三门县| 荔浦县| 台江县| 山丹县| 彭州市| 孝义市| 鸡西市|