2)然后添加Struts框架
3)创建file.jsp页面,注意在应用的模板中选择:Standard JSP using Struts 1.2/1.3
4)在file.jsp页面的BODY部分添加以下代码:(看源代码file.jsp红色字体)
Html代码
<html:form action="file_tag" method="post" enctype="multipart/form-data"> upload<html:file property="file"><br> </html:file> <html:submit value="submit"/> </html:form> you upload file:<bean:write name="file_tagForm" property="filename"/><br> size:<bean:write name="file_tagForm" property="size"/>
5)接下来创建一个Form,选择Struts 1.2 Form,Use Case名称为:File
6)创建完成后,打开FileForm.java,写入以下代码:(看源代码FileForm.java红色字体)
Java代码
private FormFile file;//定义从Form表单获得的文件 private String filename; private String size;
//并生成get和set方法省略...
7)接下来要创建个Action,来处理从Form中获得的内容,选择Struts 1.2 Action,Use Case名称为:File,选择对应得Form(FileForm.java)和输入页面(file.jsp)
8)在FileAction.java中,写入以下代码: (看源代码file.jsp红色字体)
Java代码
String dir=servlet.getServletContext().getRealPath("/upload");//获得upload文件夹的路径 FileForm fileForm=new FileForm(); FormFile f=fileForm.getFile(); String fname=f.getFileName();//获得文件名 String size=Integer.toString(f.getFileSize())+"bytes";//获得文件大小 try { InputStream in=f.getInputStream();//获得文件流 OutputStream out=new FileOutputStream(dir+"/"+fname);//定义输出流,指定存放的位置及文件名 int bytesRead=0; byte[] buffer=new byte[8192]; while((bytesRead=in.read(buffer,0,8192))!=-1){//in.read(buffer,0,8192)返回一个数值,把数据流读到buffer中,若-1数据流读取完毕 out.write(buffer, 0, bytesRead);//读出输入流到out } //关闭输入,输出流 out.close(); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } fileForm.setFilename(fname); fileForm.setSize(size); return mapping.getInputForward();
9)在WebRoot文件夹下创建upload文件夹
10)启动tomcat,并把项目部署到tomcat中
11)打开浏览器输入URL:http//localhost:8080/FileTag/file.jsp 上传一个文件,可以在tomcat目录下的webapps\FileTag\upload文件夹中找到上传得文件
转载学习: http://hi.baidu.com/zhs4310426/blog/item/37ff3fdf1c382baccc116668.html
http://12345678.iteye.com/blog/713954
[/size]