Strutsファイルアップロード(ファイルタイプ判定、サイズ判定、アップロード者情報記録等をサポート)


Strutsファイルはアップロードしてもいいです.eclipseで書いたもので、展開を解凍して走ることができます.絶対にプロジェクト全体、レンガを撮ることを歓迎します!気を失って死ぬ...キーコードのページを貼ることができません
 
<html:form action="userAction_fileUpload" method="post" enctype="multipart/form-data">
	
   		<html:text property="user.userName" value="${userForm.user.userName}"></html:text><br/>

   		<html:text property="user.userPass" value="${userForm.user.userPass}"></html:text><br/>

   		<html:file property="file" ></html:file><br/>
   		
   		<html:submit>     </html:submit>
	
	</html:form>

 
 
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	
	<filter>
		<filter-name>GBKFilter</filter-name>
		<filter-class>org.zeke.action.biz.GBKFilter</filter-class>
	</filter>
	
	<filter-mapping>
		<filter-name>GBKFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	
	
	
	<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>

 
struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>

	<form-beans>
	
		<form-bean name="userForm" type="org.zeke.actionform.UserForm" ></form-bean>
		
	</form-beans>

	<action-mappings>
		<action path="/userAction_*" 
					name="userForm" 
					type="org.zeke.action.UserAction" 
					input="/index.jsp" 
					scope="request"
					parameter="{1}"
					validate="true">
			<forward name="success" path="/index.jsp"></forward>
		</action>
		
	</action-mappings>
	
	
</struts-config>

 
 
パッケージorg.zeke.action.UserActionの下
package org.zeke.action;

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.MappingDispatchAction;
import org.apache.struts.upload.FormFile;
import org.zeke.action.biz.SaveUserInfo;
import org.zeke.action.biz.ValidateFormFile;
import org.zeke.actionform.UserForm;
import org.zeke.entity.User;

public class UserAction extends MappingDispatchAction {

	public ActionForward fileUpload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		UserForm userForm = (UserForm) form;

		User user = userForm.getUser();

		FormFile formFile = userForm.getFile();

		String path = this.getServlet().getServletContext().getRealPath("/");

		ValidateFormFile vff = new ValidateFormFile();

		if (vff.validate(formFile)) {

			SaveUserInfo saveUserInfo = new SaveUserInfo();

			boolean b = saveUserInfo.save(user, path);

			if (b) {

				saveUserInfo.saveFile(formFile, path, user.getUserName());

			}
		}else{
			
			response.setCharacterEncoding("gbk");
			response.getWriter().write("           !");
			
			return null;
		}

		return mapping.findForward("success");
	}

}

 
パッケージorg.zeke.action.biz下
 
GBKFilter.java
package org.zeke.action.biz;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class GBKFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		request.setCharacterEncoding("gbk");
		
		chain.doFilter(request, response);

	}

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

}

 
 
SaveUserInfo .java
package org.zeke.action.biz;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.struts.upload.FormFile;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.zeke.entity.User;

public class SaveUserInfo {

	public boolean saveFile(FormFile formFile,String path,String userNamePath) {
		
		boolean bl=false;
		
		String realPath = path + "\\WEB-INF\\userInfo\\"+userNamePath+"\\"+formFile.getFileName();
		
		try {
			
			InputStream ins=formFile.getInputStream();
			
			OutputStream outs=new FileOutputStream(realPath);
			
			int len=0;
			
			byte[] b=new byte[512];
			
			while((len=ins.read(b))!=-1){
				
				outs.write(b, 0, len);
				
			}
			
			outs.close();
			
			ins.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return bl;
	}

	public boolean save(User user, String path) {

		Element root = creatElement("user", null, null);

		Document document = DocumentHelper.createDocument(root);

		Element userName = creatElement("userName", user.getUserName(), null);

		root.add(userName);

		Element userPass = creatElement("userPass", user.getUserPass(), null);

		root.add(userPass);

		String realPath = path + "\\WEB-INF\\userInfo\\" + user.getUserName();

		boolean b = saveToXML(document, realPath);

		return b;
	}

	private boolean saveToXML(Document e, String path) {

		boolean b = false;

		try {

			File f = new File(path);

			if (!f.exists()) {
				f.mkdir();
			}
			File f1 = new File(f, "user.xml");

			Writer writePath = new PrintWriter(f1);

			OutputFormat outformat = new OutputFormat("    ", true);

			outformat.setEncoding("gbk");

			XMLWriter write = new XMLWriter(writePath, outformat);

			write.write(e);

			write.close();

			writePath.close();

			b = true;

		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e2) {
			e2.printStackTrace();
		}

		return b;
	}

	private Element creatElement(String nodeName, String textValue,
			Attribute[] attributes) {

		Element e = DocumentHelper.createElement(nodeName);

		if (textValue != null) {
			e.setText(textValue);
		}

		if (attributes != null) {

			if (attributes.length != 0) {

				for (Attribute a : attributes) {

					e.add(a);

				}

			}
		}

		return e;

	}

	@SuppressWarnings("unused")
	private Attribute[] createAttribute(Map<String, String> map) {

		//      
		return null;
	}

}

 
 
ValidateFormFile .java
package org.zeke.action.biz;

import org.apache.struts.upload.FormFile;

public class ValidateFormFile {
	
	public boolean validate(FormFile f){
		
		boolean b=false;
		
		if(validateName(f)&&validateSize(f)){
			
			b=true;
			
		}
		
		
		return b;
	}
	
	
	private boolean validateName(FormFile f){
		
		boolean b=false;
		
		String fileName=f.getFileName();
		
		fileName=fileName.substring(fileName.lastIndexOf('.')+1, fileName.length());
		
		String[] extension=new String[]{"pdf","doc","txt","rar"};
		
		int i=0;
		for(i=0;i<extension.length;i++){
			
			if(fileName.equalsIgnoreCase(extension[i])){
				break;
			}
			
		}
		
		if(i<extension.length){
			
			b=true;
		}
		
		return b;
	}

	private boolean validateSize(FormFile f){
		
		boolean b=false;
		
		int size=f.getFileSize();
		
		int maxSize=1024*1024*5;
		
		if(size>0&&size<=maxSize){
			b=true;
		}
		
		return b;
		
	}
	
}

 
 
package org.zeke.actionform.UserForm .java
package org.zeke.actionform;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.zeke.entity.User;

public class UserForm extends ActionForm {
	
	private static final long serialVersionUID = -863536723372815788L;

	private User user=new User();
	
	private FormFile file;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public FormFile getFile() {
		return file;
	}

	public void setFile(FormFile file) {
		this.file = file;
	}

	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		
		user.setUserName("zeke");
		user.setUserPass("root");
		
		this.setUser(user);
		
	}

	@Override
	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		
		
		
		
		return super.validate(mapping, request);
	}
	
	
	

}

 
 
 
package org.zeke.entity.User.java
package org.zeke.entity;

public class User {
	
	private String userName;
	
	private String userPass;

	public User() {	}
	
	public User(String userName, String userPass) {
		this.userName = userName;
		this.userPass = userPass;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserPass() {
		return userPass;
	}

	public void setUserPass(String userPass) {
		this.userPass = userPass;
	}
	

}

これですべてのコードが貼り付けられました...
もし必要があれば、コメントで私に言ってください.私はプロジェクト全体をあなたに送ります.共に進歩せよ!