刚刚做了三个文件上传的Demo
a.在jsp中简单利用Commons-fileupload组件实现
b.在struts1.2中实现
c.在sturts2中实现
现在把Code与大家分享一下..
注:此为三个简单Demo,仅供练习用,并没有做太多上传限制
如有兴趣可以自行查看相关文档说明
一.在JSP环境中利用Commons-fileupload组件实现文件上传
1.页面upload.jsp清单如下:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>The FileUpload Demo</title>
- </head>
-
- <body>
- <form action="UploadFile" method="post" enctype="multipart/form-data">
- <p><input type="text" name="fileinfo" value="">文件介绍</p>
- <p><input type="file" name="myfile" value="浏览文件"></p>
- <p><input type="submit" value="上 传"></p>
- </form>
- </body>
- </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>The FileUpload Demo</title>
</head>
<body>
<form action="UploadFile" method="post" enctype="multipart/form-data">
<p><input type="text" name="fileinfo" value="">文件介绍</p>
<p><input type="file" name="myfile" value="浏览文件"></p>
<p><input type="submit" value="上 传"></p>
</form>
</body>
</html>
注意:在上传表单中,既有普通文本域也有文件上传域
2.FileUplaodServlet.java清单如下:
- package org.chris.fileupload;
-
- import java.io.File;
- import java.io.IOException;
- import java.util.Iterator;
- import java.util.List;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.*;
-
- import org.apache.commons.fileupload.FileItem;
- import org.apache.commons.fileupload.FileItemFactory;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
-
- public class FileUplaodServlet extends HttpServlet {
-
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- doPost(request, response);
- }
-
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
- request.setCharacterEncoding("UTF-8");
-
-
- boolean isMultipart = ServletFileUpload.isMultipartContent(request);
-
- if(isMultipart)
- {
- try {
- FileItemFactory factory = new DiskFileItemFactory();
- ServletFileUpload fileload = new ServletFileUpload(factory);
-
-
- fileload.setSizeMax(4194304);
- List<FileItem> files = fileload.parseRequest(request);
- Iterator<FileItem> iterator = files.iterator();
- while(iterator.hasNext())
- {
- FileItem item = iterator.next();
- if(item.isFormField())
- {
- String name = item.getFieldName();
- String value = item.getString();
- System.out.println("表单域名为: " + name + "值为: " + value);
- }else
- {
-
- String filename = item.getName();
- if(filename != null)
- {
- File file = new File(filename);
-
- if(file.exists()){
- File filetoserver = new File("d:\\upload\\",file.getName());
- item.write(filetoserver);
- System.out.println("文件 " + filetoserver.getName() + " 上传成功!!");
- }
- }
- }
- }
- } catch (Exception e) {
- System.out.println(e.getStackTrace());
- }
- }
- }
- }
package org.chris.fileupload;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUplaodServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//文件的上传部分
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart)
{
try {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileload = new ServletFileUpload(factory);
// 设置最大文件尺寸,这里是4MB
fileload.setSizeMax(4194304);
List<FileItem> files = fileload.parseRequest(request);
Iterator<FileItem> iterator = files.iterator();
while(iterator.hasNext())
{
FileItem item = iterator.next();
if(item.isFormField())
{
String name = item.getFieldName();
String value = item.getString();
System.out.println("表单域名为: " + name + "值为: " + value);
}else
{
//获得获得文件名,此文件名包括路径
String filename = item.getName();
if(filename != null)
{
File file = new File(filename);
//如果此文件存在
if(file.exists()){
File filetoserver = new File("d:\\upload\\",file.getName());
item.write(filetoserver);
System.out.println("文件 " + filetoserver.getName() + " 上传成功!!");
}
}
}
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
}
}
}
}
3.web.xml清单如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.4"
- xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http:
- http:
-
- <servlet>
- <servlet-name>UploadFileServlet</servlet-name>
- <servlet-class>
- org.chris.fileupload.FileUplaodServlet
- </servlet-class>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>UploadFileServlet</servlet-name>
- <url-pattern>/UploadFile</url-pattern>
- </servlet-mapping>
-
- <welcome-file-list>
- <welcome-file>/Index.jsp</welcome-file>
- </welcome-file-list>
-
- </web-app>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>UploadFileServlet</servlet-name>
<servlet-class>
org.chris.fileupload.FileUplaodServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadFileServlet</servlet-name>
<url-pattern>/UploadFile</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/Index.jsp</welcome-file>
</welcome-file-list>
</web-app>
二.在strut1.2中实现
1.上传页面file.jsp 清单如下:
- <%@ page language="java" pageEncoding="ISO-8859-1"%>
- <%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
- <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
-
- <html>
- <head>
- <title>JSP for FileForm form</title>
- </head>
- <body>
- <html:form action="/file" enctype="multipart/form-data">
- <html:file property="file1"></html:file>
- <html:submit/><html:cancel/>
- </html:form>
- </body>
- </html>
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<html>
<head>
<title>JSP for FileForm form</title>
</head>
<body>
<html:form action="/file" enctype="multipart/form-data">
<html:file property="file1"></html:file>
<html:submit/><html:cancel/>
</html:form>
</body>
</html>
2.FileAtion.java的清单如下:
-
-
-
-
- package action;
-
- import java.io.*;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts.action.Action;
- import org.apache.struts.action.ActionForm;
- import org.apache.struts.action.ActionForward;
- import org.apache.struts.action.ActionMapping;
- import org.apache.struts.upload.FormFile;
-
- import form.FileForm;
-
-
-
-
-
-
-
-
- public class FileAction extends Action {
-
-
-
-
-
-
-
-
-
-
-
-
- public ActionForward execute(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response) {
- FileForm fileForm = (FileForm) form;
- FormFile file1=fileForm.getFile1();
- if(file1!=null){
-
- String dir=request.getSession(true).getServletContext().getRealPath("/upload");
- OutputStream fos=null;
- try {
- fos=new FileOutputStream(dir+"/"+file1.getFileName());
- fos.write(file1.getFileData(),0,file1.getFileSize());
- fos.flush();
- } catch (Exception e) {
-
- e.printStackTrace();
- }finally{
- try{
- fos.close();
- }catch(Exception e){}
- }
- }
-
- return mapping.findForward("success");
- }
- }
】
3.FileForm.java的清单如下:
- package form;
-
- 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;
-
-
-
-
-
-
-
-
- public class FileForm extends ActionForm {
-
-
-
- private FormFile file1;
-
-
-
-
-
-
- public ActionErrors validate(ActionMapping mapping,
- HttpServletRequest request) {
-
- return null;
- }
-
-
-
-
-
-
- public void reset(ActionMapping mapping, HttpServletRequest request) {
-
- }
-
- public FormFile getFile1() {
- return file1;
- }
-
- public void setFile1(FormFile file1) {
- this.file1 = file1;
- }
- }
package form;
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;
/**
* @author Chris
* Creation date: 6-27-2008
*
* XDoclet definition:
* @struts.form name="fileForm"
*/
public class FileForm extends ActionForm {
/*
* Generated Methods
*/
private FormFile file1;
/**
* Method validate
* @param mapping
* @param request
* @return ActionErrors
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
return null;
}
/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
}
public FormFile getFile1() {
return file1;
}
public void setFile1(FormFile file1) {
this.file1 = file1;
}
}
4.struts-config.xml的清单如下:
- <?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="fileForm" type="form.FileForm" />
-
- </form-beans>
-
- <global-exceptions />
- <global-forwards />
- <action-mappings >
- <action
- attribute="fileForm"
- input="/file.jsp"
- name="fileForm"
- path="/file"
- type="action.FileAction"
- validate="false">
- <forward name="success" path="/file.jsp"></forward>
- </action>
-
- </action-mappings>
-
- <message-resources parameter="ApplicationResources" />
- </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="fileForm" type="form.FileForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
<action
attribute="fileForm"
input="/file.jsp"
name="fileForm"
path="/file"
type="action.FileAction"
validate="false">
<forward name="success" path="/file.jsp"></forward>
</action>
</action-mappings>
<message-resources parameter="ApplicationResources" />
</struts-config>
5.web.xml代码清单如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.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>
- </web-app>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.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>
</web-app>
三.在struts2中实现(以图片上传为例)
1.FileUpload.jsp代码清单如下:
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%@ taglib prefix="s" uri="/struts-tags" %>
- <html>
- <head>
- <title>The FileUplaodDemo In Struts2</title>
- </head>
-
- <body>
- <s:form action="fileUpload.action" method="POST" enctype="multipart/form-data">
- <s:file name="myFile" label="MyFile" ></s:file>
- <s:textfield name="caption" label="Caption"></s:textfield>
- <s:submit label="提交"></s:submit>
- </s:form>
- </body>
- </html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>The FileUplaodDemo In Struts2</title>
</head>
<body>
<s:form action="fileUpload.action" method="POST" enctype="multipart/form-data">
<s:file name="myFile" label="MyFile" ></s:file>
<s:textfield name="caption" label="Caption"></s:textfield>
<s:submit label="提交"></s:submit>
</s:form>
</body>
</html>
2.ShowUpload.jsp的功能清单如下:
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%@ taglib prefix="s" uri="/struts-tags" %>
- <html>
- <head>
- <title>ShowUpload</title>
- </head>
-
- <body>
- <div style ="padding: 3px; border: solid 1px #cccccc; text-align: center" >
- <img src ='UploadImages/<s:property value ="imageFileName"/> '/>
- <br />
- <s:property value ="caption"/>