刚刚做了三个文件上传的Demo
a.在jsp中简单利用Commons-fileupload组件实现
b.在struts1.2中实现
c.在sturts2中实现
现在把Code与大家分享一下..
注:此为三个简单Demo,仅供练习用,并没有做太多上传限制
如有兴趣可以自行查看相关文档说明
一.在JSP环境中利用Commons-fileupload组件实现文件上传
1.页面upload.jsp清单如下:
Java代码
1.<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2.
3.
4.
5.
letFileUpload fileload = new ServletFileUpload(factory);
34.
35.// 设置最大文件尺寸,这里是4MB
36. fileload.setSizeMax(4194304);
37. List
38. Iterator
39. while(iterator.hasNext())
40. {
41. FileItem item = iterator.next();
42. if(item.isFormField())
43. {
44. String name = item.getFieldName();
45. String value = item.getString();
46. System.out.println("表单域名为: " + name + "值为: " + value);
47. }else
48. {
49. //获得获得文件名,此文件名包括路径
50. String filename = item.getName();
51. if(filename != null)
52. {
53. File file = new File(filename);
54. //如果此文件存在
55. if(file.exists()){
56. File filetoserver = new File("d:\\upload\\",file.getName());
57. item.write(filetoserver);
58. System.out.println("文件 " + filetoserver.getName() + " 上传成功!!");
59. }
60. }
61. }
62. }
63. } catch (Exception e) {
64. System.out.println(e.getStackTrace());
65. }
66. }
67. }
68.}
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 https://www.doczj.com/doc/5715471656.html,mons.fileupload.FileItem;
import https://www.doczj.com/doc/5715471656.html,mons.fileupload.FileItemFactory;
import https://www.doczj.com/doc/5715471656.html,mons.fileupload.disk.DiskFileItemFactory;
import https://www.doczj.com/doc/5715471656.html,mons.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
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清单如下:
Java代码
1.
2.
4. xmlns:xsi="https://www.doczj.com/doc/5715471656.html,/2001/XMLSchema-instance"
5. xsi:schemaLocation="https://www.doczj.com/doc/5715471656.html,/xml/ns/j2ee
6. https://www.doczj.com/doc/5715471656.html,/xml/ns/j2ee/web-app_2_4.xsd">
7.
8.
9.
10.
11. org.chris.fileupload.FileUplaodServlet
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
xmlns:xsi="https://www.doczj.com/doc/5715471656.html,/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.doczj.com/doc/5715471656.html,/xml/ns/j2ee
https://www.doczj.com/doc/5715471656.html,/xml/ns/j2ee/web-app_2_4.xsd">
org.chris.fileupload.FileUplaodServlet
二.在strut1.2中实现
1.上传页面file.jsp 清单如下:
Java代码
1.<%@ page language="java" pageEncoding="ISO-8859-1"%>
2.<%@ taglib uri="https://www.doczj.com/doc/5715471656.html,/struts/tags-bean" prefix="bean"%>
3.<%@ taglib uri="https://www.doczj.com/doc/5715471656.html,/struts/tags-html" prefix="html"%>
4.
5.
6.
7.
8.
9.
e path: templates/java/JavaClass.vtl
*/
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;
/**
* @author Chris
* Creation date: 6-27-2008
*
* XDoclet definition:
* @struts.action path="/file" name="fileForm" input="/file.jsp"
*/
public class FileAction extends Action {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
fos.close();
}catch(Exception e){}
}
}
//页面跳转
return mapping.findForward("success");
}
}
3.FileForm.java的清单如下:
Java代码
1.package form;
2.
3.import javax.servlet.http.HttpServletRequest;
4.import org.apache.struts.action.ActionErrors;
5.import org.apache.struts.action.ActionForm;
6.import org.apache.struts.action.ActionMapping;
7.import org.apache.struts.upload.FormFile;
8.
9./**
10. * @author Chris
11. * Creation date: 6-27-2008
12. *
13. * XDoclet definition:
14. * @struts.form name="fileForm"
15. */
16.public class FileForm extends ActionForm {
17. /*
18. * Generated Methods
19. */
20. private FormFile file1;
21. /**
22. * Method validate
23. * @param mapping
24. * @param request
25. * @return ActionErrors
26. */
27. public ActionErrors validate(ActionMapping mapping,
28. HttpServletRequest request) {
29. // TODO Auto-generated method stub
30. return null;
31. }
32.
33. /**
34. * Method reset
35. * @param mapping
36. * @param request
37. */
38. public void reset(ActionMapping mapping, HttpServletRequest request) {
39. // TODO Auto-generated method stub
40. }
41.
42. public FormFile getFile1() {
43. return file1;
44. }
45.
46. public void setFile1(FormFile file1) {
47. this.file1 = file1;
48. }
49.}
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的清单如下:
Java代码
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
16. input="/file.jsp"
17. name="fileForm"
18. path="/file"
19. type="action.FileAction"
20. validate="false">
21.
22.
23.
24.
25.
26.
27.
input="/file.jsp"
name="fileForm"
path="/file"
type="action.FileAction"
validate="false">
5.web.xml代码清单如下:
Java代码
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
三.在struts2中实现(以图片上传为例)
1.FileUpload.jsp代码清单如下:
Java代码
1.<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
2.<%@ taglib prefix="s" uri="/struts-tags" %>
3.
4.
代码
1.<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
2.<%@ taglib prefix="s" uri="/struts-tags" %>
3.
4.
56. in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
57. out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);
58. byte [] buffer = new byte [BUFFER_SIZE];
59. while (in.read(buffer) > 0 ) {
60. out.write(buffer);
61. }
62. } finally {
63. if ( null != in) {
64. in.close();
65. }
66. if ( null != out) {
67. out.close();
68. }
69. }
70. } catch (Exception e) {
71. e.printStackTrace();
72. }
73. }
74.
75. private static String getExtention(String fileName) {
76. int pos = https://www.doczj.com/doc/5715471656.html,stIndexOf(".");
77. return fileName.substring(pos);
78. }
79.
80. @Override
81. public String execute() {
82. imageFileName = new Date().getTime() + getExtention(fileName);
83. File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages" ) + "/" + imageFileName);
84. copy(myFile, imageFile);
85. return SUCCESS;
86. }
87.}
package com.chris;
import java.io.*;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport{
private static final long serialVersionUID = 572146812454l ;
private static final int BUFFER_SIZE = 16 * 1024 ;
//注意,文件上传时
//所以同时要提供myFileContentType,myFileFileName的set方法
private File myFile; //上传文件
private String contentType;//上传文件类型
private String fileName; //上传文件名
private String imageFileName;
private String caption;//文件说明,与页面属性绑定
public void setMyFileContentType(String contentType) {
System.out.println("contentType : " + contentType);
this .contentType = contentType;
}
public void setMyFileFileName(String fileName) {
System.out.println("FileName : " + fileName);
this .fileName = fileName;
}
public void setMyFile(File myFile) {
this .myFile = myFile;
}
public String getImageFileName() {
return imageFileName;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this .caption = caption;
}
private static void copy(File src, File dst) {
try {
InputStream in = null ;
OutputStream out = null ;
try {
in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);
byte [] buffer = new byte [BUFFER_SIZE];
while (in.read(buffer) > 0 ) {
out.write(buffer);
}
} finally {
if ( null != in) {
in.close();
}
if ( null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getExtention(String fileName) {
int pos = https://www.doczj.com/doc/5715471656.html,stIndexOf(".");
return fileName.substring(pos);
}
@Override
public String execute() {
imageFileName = new Date().getTime() + getExtention(fileName);
File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages" ) + "/" + imageFileName);
copy(myFile, imageFile);
return SUCCESS;
}
}
注:此时仅为方便实现Action所以继承ActionSupport,并Overrider execute()方法
在struts2中任何一个POJO都可以作为Action
4.struts.xml清单如下:
Java代码
1.
2.3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4. "https://www.doczj.com/doc/5715471656.html,/dtds/struts-2.0.dtd">
5.
6.
7.
8.
9.
10.
11.
12.
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"https://www.doczj.com/doc/5715471656.html,/dtds/struts-2.0.dtd">
5.web.xml清单如下:
Java代码
1.
2.
4. xmlns:xsi="https://www.doczj.com/doc/5715471656.html,/2001/XMLSchema-instance"
5. xsi:schemaLocation="https://www.doczj.com/doc/5715471656.html,/xml/ns/j2ee
6. https://www.doczj.com/doc/5715471656.html,/xml/ns/j2ee/web-app_2_4.xsd">
7.
8.
9.
10. org.apache.struts2.dispatcher.ActionContextCleanUp
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.