jsp\struts1.2\struts2 中文件上传

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> 

  注意:在上传表单中,既有普通文本域也有文件上传域

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); 
                   
//               设置最大文件尺寸,这里是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清单如下:

Java代码
<?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 清单如下:

Java代码
<%@ 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的清单如下:

Java代码
/*
* Generated by MyEclipse Struts
* Template 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的清单如下:

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代码
<?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>

三.在struts2中实现(以图片上传为例)

1.FileUpload.jsp代码清单如下:

Java代码
<%@ 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的功能清单如下:

Java代码
<%@ 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"/>
</div >
</body>
</html>

3.FileUploadAction.java的代码清单如下 :

Java代码
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 ; //注意,文件上传时<s:file/>同时与myFile,myFileContentType,myFileFileName绑定
//所以同时要提供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 = fileName.lastIndexOf(".");
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代码
<?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>
<package name="example" namespace="/" extends="struts-default">
<action name="fileUpload" class="com.chris.FileUploadAction">
<interceptor-ref name="fileUploadStack"/>
<result>/ShowUpload.jsp</result>
</action>
</package>
</struts>

5.web.xml清单如下:

Java代码
<?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">
<filter >
<filter-name > struts-cleanup </filter-name >
<filter-class >
org.apache.struts2.dispatcher.ActionContextCleanUp
</filter-class >
</filter >
<filter-mapping >
<filter-name > struts-cleanup </filter-name >
<url-pattern > /* </url-pattern >
</filter-mapping > <filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>Index.jsp</welcome-file>
</welcome-file-list> </web-app>

jsp\struts1.2\struts2 中文件上传(转)的更多相关文章

  1. Struts2中文件上传下载实例

    1.单文件上传 jsp页面: <!-- 单文件上传 --> <form action="Fileupload.action" method="post& ...

  2. struts2中文件上传

    注意点 private File image;//对应的就是表单中文件上传的那个输入域的名称,Struts2框架会封装成File类型的 private String imageFileName;// ...

  3. struts2的文件上传和文件下载

    实现使用Struts2文件上传和文件下载: 注意点: (1)对应表单的file1和私有成员变量的名称必须一致 <input type="file" name="fi ...

  4. 【Struts2】文件上传与下载

    一.上传 1.1 Struts2实现步骤 浏览器端 服务器端 1.2 关于Struts2中文件上传细节: 1.3 示例 jsp文件 Action类 struts.xml文件配置 二.下载 2.1 文件 ...

  5. Struts2之文件上传与下载

    时间:2017-1-11 15:47 --使用commons-fileupload组件上传1.客户端    *   method="post"    *   <input t ...

  6. struts2的文件上传

    在做B/S系统时,通常会涉及到上传文件和下载文件,在没接struts2框架之前,我们都是使用apache下面的commons子项目的FileUpload组件来进行文件的上传,但是那样做的话,代码看起来 ...

  7. Struts2+Uploadify文件上传使用详解

    Uploadify是JQuery的一个上传插件,实现的效果非常不错,带进度显示.不过官方提供的实例是php版本的,本文将详细介绍Uploadify在java中的使用,您也可以点击下面的链接进行演示或下 ...

  8. Struts2图片文件上传,判断图片格式和图片大小

    1. 配置Struts2能够上传的最大文件大小 使用Struts2进行文件上传的时候,Struts2默认文件大小最大为2MB,如果要传大一点的文件,就需要修改struts.xml配置文件,重新设置能够 ...

  9. struts2实现文件上传和下载

    在做B/S系统时,通常会涉及到上传文件和下载文件,在没接struts2框架之前,我们都是使用apache下面的commons子项目的FileUpload组件来进行文件的上传,但是那样做的话,代码看起来 ...

随机推荐

  1. mongodb学习03 操作详解

    插入文档 db.test.insert({"name":"jinks"}); 批量插入 db.test.insert([{}, {}, {}]); 一次批量插入 ...

  2. HTML5中createPattern()

    定义和用法 createPattern() 方法在指定的方向内重复指定的元素. 元素可以是图片.视频,或者其他 <canvas> 元素. 被重复的元素可用于绘制/填充矩形.圆形或线条等等. ...

  3. underscore.js依赖库函数分析二(查找)

    查找: 在underscore.js封装了对dom查找的操作,find()和filter()函数,find()函数的查找操作是返回首个与条件相符的元素值,filter()函数是找到与条件相符的所有元素 ...

  4. Cache的使用

    公共方法Add 将指定项添加到 Cache 对象,该对象具有依赖项.过期和优先级策略以及一个委托(可用于在从 Cache 移除插入项时通知应用程序). Equals(从 Object 继承) 已重载. ...

  5. 【原】iOS学习之PCH文件

    1. PCH文件概述 PCH文件是一种预编译头文件(一般扩展名为.PCH),是把一个工程中较稳定的代码预先编译好放在一个文件(.PCH)里.这些预先编译好的代码可以是任何的C/C++代码--甚至可以是 ...

  6. 盐水的故事[HDU1408]

    盐水的故事Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submissio ...

  7. 20145308刘昊阳 《Java程序设计》第7周学习总结

    20145308刘昊阳 <Java程序设计>第7周学习总结 教材学习内容总结 第13章 时间与日期 13.1 认识时间与日期 13.1.1 时间的度量 格林威治时间(GMT) 世界时(UT ...

  8. ACM 寻找最大数

    寻找最大数 时间限制:1000 ms  |  内存限制:65535 KB 难度:2   描述 请在整数 n 中删除m个数字, 使得余下的数字按原次序组成的新数最大, 比如当n=920813467185 ...

  9. ACM: HDU 2563 统计问题-DFS+打表

    HDU 2563 统计问题 Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u HDU 2 ...

  10. [深入浅出WP8.1(Runtime)]Toast通知

    9.1 Toast通知 Toast通知是在屏幕最顶上弹出来的临时通知,是Windows Phone通用的弹出式短暂的通知,默认的系统消息都是采用Toast通知的形式,比如当你手机收到短信的时候,在手机 ...