上传:
第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载。
第二步:把form表的enctype设置为:“multipart/form-data“,如下:
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
<input type="file" name="uploadFile">
</form>
第三步:在Action类中添加以下属性,属性红色部分对应于表单中文件字段的名称:
public class HelloWorldAction{
private File uploadFile;//得到上传的文件
private String uploadFileContentType;//得到文件的类型
private String uploadFileFileName;//得到文件的名称
//这里略省了属性的getter/setter方法
public String upload() throws Exception{
String realpath =
ServletActionContext.getServletContext().getRealPath("/images");
File file = new File(realpath);
if(!file.exists()) file.mkdirs();
FileUtils.copyFile(uploadFile, new File(file, uploadFileFileName));
return "success";
}
}
//
例子:
//action 代码。
package com.
struts2;
import java.io.File;
import com.opensymphony.xwork2.ActionSupport;
public class UpLoadAction extends ActionSupport {
private File photo;
private String photoFileName;
private String photoContentType;
public String execute() throws Exception {
System.out.println(photo);
System.out.println(photoFileName);
System.out.println(photoContentType);
//拷贝上传文件到那个俄路径下。
photo.renameTo(new File("c:\\" + photoFileName));
return "success";
}
public void setPhoto(File photo) {
this.photo = photo;
}
public void setPhotoFileName(String photoFileName) {
this.photoFileName = photoFileName;
}
public void setPhotoContentType(String photoContentType) {
this.photoContentType = photoContentType;
}
}
//配置文件 struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software
Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="com" namespace="/zdy" extends="struts-default">
<action name="hello" class="com.struts2.HelloWordAction">
<result>/hello.jsp</result>
</action>
<action name="nod">
<result>/hello.jsp</result>
</action>
<action name="add" class="com.struts2.AddAction">
<result name="input">add-input.jsp</result>
<result>add-result.jsp</result>
<result name="cal">\add-result.jsp</result>
</action>
<action name="upLoadAction" class="com.struts2.UpLoadAction"/>
</package>
</struts>
//jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!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=GB18030">
<title>Insert title here</title>
</head>
<body>
<form action="upLoadAction.action" method="post" enctype="multipart/form-data">
name:<input type="text" name="name"/><br/>
file:<input type="file" name="photo"/><br/>
<input type="submit" value="提交"/><br/>
</form>
</body>
</html>