<![endif]--> <![endif]--> <![endif]-->
在 struts 2 的文件上传操作比 struts1 更简单方便。
struts1 的文件上传请看: http://blog.youkuaiyun.com/zhanggnol/archive/2011/01/05/6118895.aspx
本文讲解如何使用 struts2 上传文件。
步骤:
1 编写 jsp 页面
2 编写 Action ,处理文件上传功能
3 配置 struts.xml 文件
5 测试
1、 jsp 页面 —upload_form.jsp
<%@ page language = "java" contentType = "text/html; charset=ISO-8859-1" pageEncoding = "ISO-8859-1" %> <! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > < html > < head > < meta http-equiv = "Content-Type" content = "text/html; charset=ISO-8859-1" > < title > Upload File </ title > </ head > < body > < form action = " upload.action " method = "post" enctype = " multipart/form-data " > < input type = "file" name = "file" > < input type = "submit" value = "Submit" /> </ form > </ body > </ html > |
2 、编写 UploadAction 类,实现文件上传功能
public class UploadAction { public static Logger logger = Logger.getLogger(UploadAction.class);
private File file;
public File getFile() { return file; }
public void setFile(File file) { logger.debug("file set ... "); this.file = file; }
public String execute() { try { // 创建输入流 FileInputStream fis = new FileInputStream(file);
// 将文件保存 在服务器端的 "upload" 文件夹下 File outFile = new File(ServletActionContext.getServletContext() .getRealPath("upload"), file.getName());
// 将输入流中的字节读出 通过输出流向保存的文件中写入 BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(outFile)); int b = -1; while ((b = fis.read()) != -1) { bos.write(b); }
logger.debug("outFile path : " + outFile.getPath());
bos.close(); fis.close();
} catch (Exception e) { e.printStackTrace(); return "fail"; }
return "success"; }
} |
注意 1 : struts2 与 struts1 不同,不需要单独的配置一个 ActionForm 。
注意 2 :在 struts2 中,将页面提交的文件直接封装成一个 java.io.File 对象。
3 配置 struts.xml 文件
<? xml version = "1.0" encoding = "UTF-8" ?> <! DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd" > < struts >
< package name = "package-one" extends = "struts-default" namespace = "/one" >
< action name = "show" class = "zl.action.ShowAction" > < result name = "success" > /upload_form.jsp </ result > </ action >
< action name = "upload" class = "zl.action.UploadAction" > < result name = "success" > /success.jsp </ result > < result name = "fail" > show.action </ result > </ action >
</ package >
</ struts > |
4 测试
提交后,会将 Log4j 的信息打印在 console 上,文件保存的 path 。
21:47:00,343 DEBUG UploadAction:20 - file set ... 21:47:02,328 DEBUG UploadAction:35 - outFile path : D:/Program Files/tomcat6.0/webapps/test3/upload/upload_71f9e496_12d56642ee9__8000_00000001.tmp |