//action的代码
package cn.itcast.actions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;
import cn.itcast.forms.FileUploadForm;
public class UploadFileAction extends DispatchAction {
public ActionForward uploadFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//这是清空缓存
response.addHeader("cache-control", "no-cache");
response.addHeader("expires", "0");
response.addHeader("pragma", "no-cache");
FileUploadForm fileUploadForm = (FileUploadForm)form;
String savePath = request.getSession().getServletContext().getRealPath("/upload");
//这是判断这个目录是否存在,如果存在就不建立,如果不存在就建立一个目录
File file2 = new File(savePath);
if(!file2.exists())
{
file2.mkdirs();
}
//这是删除原来存在的文件
File[] files = file2.listFiles();
System.out.println(files.length);
if(files.length > 0)
{
for (int i = 0; i < files.length; i++) {
files[i].delete();
}
}
OutputStream out = null;
InputStream in = null;
System.out.println(fileUploadForm.getCount());
for(int i = 0; i < fileUploadForm.getCount(); i++)
{
FormFile file = fileUploadForm.getUploadfile(i);
in = file.getInputStream();
byte [] buffer = new byte[1024];
int len = 0;
//这是给每个文件取一个不同名字
UUID uuid = UUID.randomUUID();
String prefix = uuid.toString();
String subbfix = file.getFileName().substring(file.getFileName().lastIndexOf("."));
String fileName = prefix + subbfix;
File file3 = new File(file2, fileName);
len = in.read(buffer);
out = new FileOutputStream(file3);
while(len > 0)
{
//这是给文件取名字
out.write(buffer, 0, len);
len = in.read(buffer);
}
out.flush();
}
in.close();
out.close();
//每提交一次就会清空list中原来存在的文件,这样可以防止当我们第二次提交的时候会提交重复的文件
fileUploadForm.getList().clear();
return mapping.findForward("success");
}
}
//form的代码
package cn.itcast.forms;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class FileUploadForm extends ActionForm implements Serializable {
private List<FormFile> list = new ArrayList<FormFile>();
public List<FormFile> getList() {
return list;
}
public void setList(List<FormFile> list) {
this.list = list;
}
public FormFile getUploadfile(int i)
{
return list.get(i);
}
public void setUploadfile(int i, FormFile file)
{
//只有上传文件的字节数大于0,才能够上传
if(file.getFileSize() > 0)
{
list.add(file);
}
}
//这是得到文件的数量
public int getCount()
{
return list.size();
}
}
//struts-config的代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<data-sources />
<form-beans>
<form-bean name="uploadForm" type="cn.itcast.forms.FileUploadForm"></form-bean>
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings>
<action path="/upload" name="uploadForm" type="cn.itcast.actions.UploadFileAction" parameter="p">
<forward name="success" path="/success.jsp"></forward>
</action>
</action-mappings>
<!-- 配置文件上传大小 -->
<!-- 规定了最大上传大小是2M,如果设置成-1则大小无限制了 -->
<controller maxFileSize="-1" />
<message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>
//web.xml的代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
//jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'upload.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="js/jquery-1.2.6.js"></script>
<script type="text/javascript">
var i = 0;
function addFile(it)
{
var c = $(it).next().clone(true);
i++;
c.children("input").attr("name","uploadfile["+i+"]");
var p = $("form input:last").prev();
p.after(c);
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload.do?p=uploadFile" method="post" enctype="multipart/form-data"><input type="button" οnclick="addFile(this)" value="增加"/>
<div><input type="file" name="uploadfile[0]"/><br/></div>
<input type="submit" value="提交"/>
</form>
</body>
</html>