fileupload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<h1>Action文件上传</h1>
<s:form method="post" enctype="multipart/form-data" action="up">
<s:file label="上传文件" name="file" />
<s:submit></s:submit>
</s:form>
</body>
</html>
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>
<!-- 为了使用struts2提供的功能,需要继承系统提供的包default -->
<package name="struts2" extends="struts-default">
<!-- 文件上传 -->
<action name="up" class="com.fileupload.UploadAction">
<interceptor-ref name="execAndWait"/>
<result name="wait">/wait.jsp</result>
<result >/ok.jsp</result>
</action>
</package>
</struts>
struts.properties
struts.devMode=false
struts.ognl.allowStaticMethodAccess=true
struts.multipart.saveDir=d:/
struts.multipart.maxSize=4097152
UploadAction.java
package com.fileupload;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
public class UploadAction implements Action {
private File file;
private String contentType;
private String fileName;
public void setFile(File file) {
this.file = file;
}
public void setFileContentType(String contentType) {
this.contentType = contentType;
}
public void setFileFileName(String fileName) {
this.fileName = fileName;
}
public String execute() {
String path = ServletActionContext.getServletContext().getRealPath("");
try {
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(path+"/"+fileName);
byte[] bytes = new byte[1024];
int num = 0;
while((num = fis.read(bytes))>0){
fos.write(bytes,0,num);
}
fos.flush();
fos.close();
fis.close();
System.out.println("ok");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
}
File
ContentType
FileName
这三个属性是必须的,在写set方法时必须是:
setFile setFileContentType setFileFileName