posts - 403, comments - 310, trackbacks - 0, articles - 7
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Struts 学习笔记(3) - 文件上传的实现

Posted on 2007-05-01 21:04 ZelluX 阅读(453) 评论(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


只有注册用户登录后才能发表评论。


网站导航: