zs453898875

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

本文介绍了:
1.基于表单的文件上传
2.Struts 2 的文件下载
3.Struts2.文件上传
4.使用FileInputStream FileOutputStream文件流来上传
5.使用FileUtil上传
6.使用IOUtil上传
7.使用IOUtil上传
8.使用数组上传多个文件
9.使用List上传多个文件

----1.基于表单的文件上传-----
fileupload.jsp

Html代码 复制代码 收藏代码
  1. <body>  
  2.     <form action="showFile.jsp" name="myForm" method="post" enctype="multipart/form-data">  
  3.         选择上传的文件   
  4.         <input type="file" name="myfile"><br/><br/>  
  5.         <input type="submit" name="mySubmit" value="上传"/>    
  6.     </form>  
  7.  </body>  
 <body>
  	<form action="showFile.jsp" name="myForm" method="post" enctype="multipart/form-data">
  		选择上传的文件
  		<input type="file" name="myfile"><br/><br/>
  		<input type="submit" name="mySubmit" value="上传"/> 
  	</form>
  </body>


showFile.jsp

Html代码 复制代码 收藏代码
  1. <body>  
  2.      上传的文件的内容如下:   
  3.      <%   
  4.      InputStream is=request.getInputStream();   
  5.      InputStreamReader isr=new InputStreamReader(is);   
  6.      BufferedReader br=new BufferedReader(isr);   
  7.      String content=null;   
  8.      while((content=br.readLine())!=null){   
  9.          out.print(content+"<br/>");   
  10.      }   
  11.      %>  
  12.   </body>  
<body>
     上传的文件的内容如下:
     <%
     InputStream is=request.getInputStream();
     InputStreamReader isr=new InputStreamReader(is);
     BufferedReader br=new BufferedReader(isr);
     String content=null;
     while((content=br.readLine())!=null){
    	 out.print(content+"<br/>");
     }
     %>
  </body>



----2.手动上传-----

Java代码 复制代码 收藏代码
  1. 通过二进制刘获取上传文件的内容,并将上传的文件内容保存到服务器的某个目录,这样就实现了文件上传。由于这个处理过程完全依赖与开发自己处理二进制流,所以也称为“手动上传”。   
  2. 从上面的第一个例子可以看到,使用二进制流获取的上传文件的内容与实际文件的内容有还是有一定的区别,包含了很多实际文本中没有的字符。所以需要对获取的内容进行解析,去掉额外的字符。  
通过二进制刘获取上传文件的内容,并将上传的文件内容保存到服务器的某个目录,这样就实现了文件上传。由于这个处理过程完全依赖与开发自己处理二进制流,所以也称为“手动上传”。
从上面的第一个例子可以看到,使用二进制流获取的上传文件的内容与实际文件的内容有还是有一定的区别,包含了很多实际文本中没有的字符。所以需要对获取的内容进行解析,去掉额外的字符。



----3 Struts2.文件上传----

Java代码 复制代码 收藏代码
  1. Struts2中使用Common-fileUpload文件上传框架,需要在web应用中增加两个Jar 文件, 即 commons-fileupload.jar. commons-io.jar   
  2.   
  3. 需要使用fileUpload拦截器:具体的说明在 struts2-core-2.3.4.jar \org.apache.struts2.interceptor\FileUploadInterceptor.class 里面    
  4. 下面来看看一点源代码  
Struts2中使用Common-fileUpload文件上传框架,需要在web应用中增加两个Jar 文件, 即 commons-fileupload.jar. commons-io.jar

需要使用fileUpload拦截器:具体的说明在 struts2-core-2.3.4.jar \org.apache.struts2.interceptor\FileUploadInterceptor.class 里面 
下面来看看一点源代码

 

Java代码 复制代码 收藏代码
  1. public class FileUploadInterceptor extends AbstractInterceptor {   
  2.   
  3.     private static final long serialVersionUID = -4764627478894962478L;   
  4.   
  5.     protected static final Logger LOG = LoggerFactory.getLogger(FileUploadInterceptor.class);   
  6.     private static final String DEFAULT_MESSAGE = "no.message.found";   
  7.   
  8.     protected boolean useActionMessageBundle;   
  9.   
  10.     protected Long maximumSize;   
  11.     protected Set<String> allowedTypesSet = Collections.emptySet();   
  12.     protected Set<String> allowedExtensionsSet = Collections.emptySet();   
  13.   
  14.     private PatternMatcher matcher;   
  15.   
  16.  @Inject  
  17.     public void setMatcher(PatternMatcher matcher) {   
  18.         this.matcher = matcher;   
  19.     }   
  20.   
  21.     public void setUseActionMessageBundle(String value) {   
  22.         this.useActionMessageBundle = Boolean.valueOf(value);   
  23.     }   
  24.   
  25.     //这就是struts.xml 中param为什么要配置为 allowedExtensions   
  26.     public void setAllowedExtensions(String allowedExtensions) {   
  27.         allowedExtensionsSet = TextParseUtil.commaDelimitedStringToSet(allowedExtensions);   
  28.     }   
  29.     //这就是struts.xml 中param为什么要配置为 allowedTypes 而不是 上面的allowedTypesSet    
  30.     public void setAllowedTypes(String allowedTypes) {   
  31.         allowedTypesSet = TextParseUtil.commaDelimitedStringToSet(allowedTypes);   
  32.     }   
  33.   
  34.     public void setMaximumSize(Long maximumSize) {   
  35.         this.maximumSize = maximumSize;   
  36.     }   
  37. }  
public class FileUploadInterceptor extends AbstractInterceptor {

    private static final long serialVersionUID = -4764627478894962478L;

    protected static final Logger LOG = LoggerFactory.getLogger(FileUploadInterceptor.class);
    private static final String DEFAULT_MESSAGE = "no.message.found";

    protected boolean useActionMessageBundle;

    protected Long maximumSize;
    protected Set<String> allowedTypesSet = Collections.emptySet();
    protected Set<String> allowedExtensionsSet = Collections.emptySet();

    private PatternMatcher matcher;

 @Inject
    public void setMatcher(PatternMatcher matcher) {
        this.matcher = matcher;
    }

    public void setUseActionMessageBundle(String value) {
        this.useActionMessageBundle = Boolean.valueOf(value);
    }

    //这就是struts.xml 中param为什么要配置为 allowedExtensions
    public void setAllowedExtensions(String allowedExtensions) {
        allowedExtensionsSet = TextParseUtil.commaDelimitedStringToSet(allowedExtensions);
    }
    //这就是struts.xml 中param为什么要配置为 allowedTypes 而不是 上面的allowedTypesSet 
    public void setAllowedTypes(String allowedTypes) {
        allowedTypesSet = TextParseUtil.commaDelimitedStringToSet(allowedTypes);
    }

    public void setMaximumSize(Long maximumSize) {
        this.maximumSize = maximumSize;
    }
}

 

Html代码 复制代码 收藏代码
  1. 官员文件初始值大小 上面的类中的说明   
  2. <li>maximumSize (optional) - the maximum size (in bytes) that the interceptor will allow a file reference to be set   
  3.  * on the action. Note, this is <b>not</b> related to the various properties found in struts.properties.   
  4.  * Default to approximately 2MB.</li>  
  5. 具体说的是这个值在struts.properties 中有设置。 下面就来看 里面的设置   
  6.   
  7. ### Parser to handle HTTP POST requests, encoded using the MIME-type multipart/form-data   
  8.   
  9. 文件上传解析器     
  10. struts.multipart.parser=cos  
  11. struts.multipart.parser=pell  
  12. #默认 使用jakata框架上传文件   
  13. struts.multipart.parser=jakarta  
  14.   
  15. #上传时候 默认的临时文件目录     
  16. # uses javax.servlet.context.tempdir by default   
  17. struts.multipart.saveDir=   
  18.   
  19. #上传时候默认的大小   
  20. struts.multipart.maxSize=2097152  
官员文件初始值大小 上面的类中的说明
<li>maximumSize (optional) - the maximum size (in bytes) that the interceptor will allow a file reference to be set
 * on the action. Note, this is <b>not</b> related to the various properties found in struts.properties.
 * Default to approximately 2MB.</li>
具体说的是这个值在struts.properties 中有设置。 下面就来看 里面的设置

### Parser to handle HTTP POST requests, encoded using the MIME-type multipart/form-data

文件上传解析器  
# struts.multipart.parser=cos
# struts.multipart.parser=pell
#默认 使用jakata框架上传文件
struts.multipart.parser=jakarta

#上传时候 默认的临时文件目录  
# uses javax.servlet.context.tempdir by default
struts.multipart.saveDir=

#上传时候默认的大小
struts.multipart.maxSize=2097152



案例:使用FileInputStream FileOutputStream文件流来上传
action.java

Java代码 复制代码 收藏代码
  1. package com.sh.action;   
  2.   
  3. import java.io.File;   
  4. import java.io.FileInputStream;   
  5. import java.io.FileOutputStream;   
  6.   
  7. import org.apache.struts2.ServletActionContext;   
  8.   
  9. import com.opensymphony.xwork2.ActionSupport;   
  10.   
  11. public class MyUpAction extends ActionSupport {   
  12.        
  13.     private File upload; //上传的文件   
  14.     private String uploadContentType; //文件的类型   
  15.     private String uploadFileName; //文件名称   
  16.     private String savePath; //文件上传的路径   
  17.        
  18. //注意这里的保存路径   
  19.     public String getSavePath() {   
  20.         return ServletActionContext.getRequest().getRealPath(savePath);   
  21.     }   
  22.     public void setSavePath(String savePath) {   
  23.         this.savePath = savePath;   
  24.     }   
  25.     @Override  
  26.     public String execute() throws Exception {   
  27.         System.out.println("type:"+this.uploadContentType);   
  28.         String fileName=getSavePath()+"\\"+getUploadFileName();   
  29.         FileOutputStream fos=new FileOutputStream(fileName);   
  30.         FileInputStream fis=new FileInputStream(getUpload());   
  31.         byte[] b=new byte[1024];   
  32.         int len=0;   
  33.         while ((len=fis.read(b))>0) {   
  34.             fos.write(b,0,len);   
  35.         }   
  36.         fos.flush();   
  37.         fos.close();   
  38.         fis.close();   
  39.         return SUCCESS;   
  40.     }   
  41. //get set   
  42. }  
package com.sh.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class MyUpAction extends ActionSupport {
	
	private File upload; //上传的文件
	private String uploadContentType; //文件的类型
	private String uploadFileName; //文件名称
	private String savePath; //文件上传的路径
	
//注意这里的保存路径
	public String getSavePath() {
		return ServletActionContext.getRequest().getRealPath(savePath);
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	@Override
	public String execute() throws Exception {
		System.out.println("type:"+this.uploadContentType);
		String fileName=getSavePath()+"\\"+getUploadFileName();
		FileOutputStream fos=new FileOutputStream(fileName);
		FileInputStream fis=new FileInputStream(getUpload());
		byte[] b=new byte[1024];
		int len=0;
		while ((len=fis.read(b))>0) {
			fos.write(b,0,len);
		}
		fos.flush();
		fos.close();
		fis.close();
		return SUCCESS;
	}
//get set
}



struts.xml

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC   
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"   
  4.     "http://struts.apache.org/dtds/struts-2.3.dtd">  
  5.   
  6. <struts>    
  7.     <constant name="struts.i18n.encoding" value="utf-8"/>  
  8.     <constant name="struts.devMode" value="true"/>     
  9.     <constant name="struts.convention.classes.reload" value="true" />    
  10.        
  11.     <constant name="struts.multipart.saveDir" value="f:/tmp"/>  
  12.     <package name="/user" extends="struts-default">  
  13.         <action name="up" class="com.sh.action.MyUpAction">  
  14.             <result name="input">/up.jsp</result>  
  15.             <result name="success">/success.jsp</result>  
  16.             <!-- 在web-root目录下新建的一个 upload目录 用于保存上传的文件 -->  
  17.             <param name="savePath">/upload</param>  
  18.             <interceptor-ref name="fileUpload">  
  19.                 <!--采用设置文件的类型 来限制上传文件的类型-->  
  20.                 <param name="allowedTypes">text/plain</param>  
  21.                 <!--采用设置文件的后缀来限制上传文件的类型 -->  
  22.                 <param name="allowedExtensions">png,txt</param>  
  23.                 <!--设置文件的大小 默认为 2M [单位:byte] -->  
  24.                 <param name="maximumSize">1024000</param>  
  25.             </interceptor-ref>               
  26.                        
  27.             <interceptor-ref name="defaultStack"/>  
  28.         </action>  
  29.     </package>  
  30. </struts>  
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts> 
    <constant name="struts.i18n.encoding" value="utf-8"/>
    <constant name="struts.devMode" value="true"/>  
    <constant name="struts.convention.classes.reload" value="true" /> 
    
    <constant name="struts.multipart.saveDir" value="f:/tmp"/>
    <package name="/user" extends="struts-default">
    	<action name="up" class="com.sh.action.MyUpAction">
    		<result name="input">/up.jsp</result>
			<result name="success">/success.jsp</result>
			<!-- 在web-root目录下新建的一个 upload目录 用于保存上传的文件 -->
			<param name="savePath">/upload</param>
			<interceptor-ref name="fileUpload">
				<!--采用设置文件的类型 来限制上传文件的类型-->
				<param name="allowedTypes">text/plain</param>
				<!--采用设置文件的后缀来限制上传文件的类型 -->
				<param name="allowedExtensions">png,txt</param>
				<!--设置文件的大小 默认为 2M [单位:byte] -->
				<param name="maximumSize">1024000</param>
			</interceptor-ref>			
			    	
			<interceptor-ref name="defaultStack"/>
    	</action>
    </package>
</struts>


up.jsp

Html代码 复制代码 收藏代码
  1. <body>  
  2.   <h2>Struts2 上传文件</h2>  
  3.    <s:fielderror/>  
  4.   <s:form action="up" method="post" name="upform" id="form1" enctype="multipart/form-data" theme="simple">  
  5.         选择文件:   
  6.        <s:file name="upload" cssStyle="width:300px;"/>  
  7.        <s:submit value="确定"/>  
  8.   </s:form>         
  9. </body>  
  <body>
    <h2>Struts2 上传文件</h2>
     <s:fielderror/>
    <s:form action="up" method="post" name="upform" id="form1" enctype="multipart/form-data" theme="simple">
          选择文件:
         <s:file name="upload" cssStyle="width:300px;"/>
         <s:submit value="确定"/>
    </s:form>      
  </body>


success.jsp

Html代码 复制代码 收藏代码
  1. <body>  
  2.   <b>上传成功!</b>  
  3.   <s:property value="uploadFileName"/><br/>  
  4.   [img]<s:property value="'upload/'+uploadFileName"/>[/img]   
  5. </body>  
  <body>
    <b>上传成功!</b>
    <s:property value="uploadFileName"/><br/>
    [img]<s:property value="'upload/'+uploadFileName"/>[/img]
  </body>



案例:使用FileUtil上传

action.java

Java代码 复制代码 收藏代码
  1. package com.sh.action;   
  2.   
  3. import java.io.File;   
  4. import java.io.IOException;   
  5. import java.text.DateFormat;   
  6. import java.text.SimpleDateFormat;   
  7. import java.util.Date;   
  8. import java.util.Random;   
  9. import java.util.UUID;   
  10.   
  11. import org.apache.commons.io.FileUtils;   
  12. import org.apache.struts2.ServletActionContext;   
  13.   
  14. import com.opensymphony.xwork2.ActionContext;   
  15. import com.opensymphony.xwork2.ActionSupport;   
  16.   
  17. public class FileUtilUpload extends ActionSupport {   
  18.     private File image; //文件   
  19.     private String imageFileName; //文件名   
  20.     private String imageContentType;//文件类型   
  21.     public String execute(){   
  22.         try {   
  23.             if(image!=null){   
  24.                 //文件保存的父目录   
  25.                 String realPath=ServletActionContext.getServletContext()   
  26.                 .getRealPath("/image");   
  27.                 //要保存的新的文件名称   
  28.                 String targetFileName=generateFileName(imageFileName);   
  29.                 //利用父子目录穿件文件目录   
  30.                 File savefile=new File(new File(realPath),targetFileName);   
  31.                 if(!savefile.getParentFile().exists()){   
  32.                     savefile.getParentFile().mkdirs();   
  33.                 }   
  34.                 FileUtils.copyFile(image, savefile);   
  35.                 ActionContext.getContext().put("message""上传成功!");   
  36.                 ActionContext.getContext().put("filePath", targetFileName);   
  37.             }   
  38.         } catch (IOException e) {   
  39.             // TODO Auto-generated catch block   
  40.             e.printStackTrace();   
  41.         }   
  42.         return "success";   
  43.     }   
  44.        
  45.     /**  
  46.      * new文件名= 时间 + 随机数  
  47.      * @param fileName: old文件名  
  48.      * @return new文件名  
  49.      */  
  50.     private String generateFileName(String fileName) {   
  51.         //时间   
  52.         DateFormat df = new SimpleDateFormat("yyMMddHHmmss");      
  53.         String formatDate = df.format(new Date());   
  54.         //随机数   
  55.         int random = new Random().nextInt(10000);    
  56.         //文件后缀   
  57.         int position = fileName.lastIndexOf(".");      
  58.         String extension = fileName.substring(position);      
  59.         return formatDate + random + extension;      
  60.     }   
  61. //get set   
  62.   
  63. }  
package com.sh.action;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class FileUtilUpload extends ActionSupport {
	private File image; //文件
	private String imageFileName; //文件名
	private String imageContentType;//文件类型
	public String execute(){
		try {
			if(image!=null){
				//文件保存的父目录
				String realPath=ServletActionContext.getServletContext()
				.getRealPath("/image");
				//要保存的新的文件名称
				String targetFileName=generateFileName(imageFileName);
				//利用父子目录穿件文件目录
				File savefile=new File(new File(realPath),targetFileName);
				if(!savefile.getParentFile().exists()){
					savefile.getParentFile().mkdirs();
				}
				FileUtils.copyFile(image, savefile);
				ActionContext.getContext().put("message", "上传成功!");
				ActionContext.getContext().put("filePath", targetFileName);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "success";
	}
	
	/**
	 * new文件名= 时间 + 随机数
	 * @param fileName: old文件名
	 * @return new文件名
	 */
	private String generateFileName(String fileName) {
		//时间
        DateFormat df = new SimpleDateFormat("yyMMddHHmmss");   
        String formatDate = df.format(new Date());
        //随机数
        int random = new Random().nextInt(10000); 
        //文件后缀
        int position = fileName.lastIndexOf(".");   
        String extension = fileName.substring(position);   
        return formatDate + random + extension;   
    }
//get set

}


struts.xml

Xml代码 复制代码 收藏代码
  1. <action name="fileUtilUpload" class="com.sh.action.FileUtilUpload">  
  2.     <result name="input">/fileutilupload.jsp</result>  
  3.     <result name="success">/fuuSuccess.jsp</result>  
  4. </action>  
	
    	<action name="fileUtilUpload" class="com.sh.action.FileUtilUpload">
    		<result name="input">/fileutilupload.jsp</result>
    		<result name="success">/fuuSuccess.jsp</result>
    	</action>


fileutilupload.jsp

Html代码 复制代码 收藏代码
  1. <form action="${pageContext.request.contextPath }/fileUtilUpload.action"    
  2.    enctype="multipart/form-data" method="post">  
  3.     文件:<input type="file" name="image"/>  
  4.     <input type="submit" value="上传"/>  
  5.    </form>  
 <form action="${pageContext.request.contextPath }/fileUtilUpload.action" 
    enctype="multipart/form-data" method="post">
    	文件:<input type="file" name="image"/>
    	<input type="submit" value="上传"/>
    </form>



fuuSuccess.jsp

Html代码 复制代码 收藏代码
  1. body>  
  2.     <b>${message}</b>  
  3.         ${imageFileName}<br/>  
  4.     <img src="upload/${filePath}"/>  
  5.   </body>  
body>
    <b>${message}</b>
   		${imageFileName}<br/>
    <img src="upload/${filePath}"/>
  </body>



案例:使用IOUtil上传

action.java

Java代码 复制代码 收藏代码
  1. package com.sh.action;   
  2.   
  3. import java.io.File;   
  4. import java.io.FileInputStream;   
  5. import java.io.FileOutputStream;   
  6. import java.text.DateFormat;   
  7. import java.text.SimpleDateFormat;   
  8. import java.util.Date;   
  9. import java.util.UUID;   
  10.   
  11. import org.apache.commons.io.IOUtils;   
  12. import org.apache.struts2.ServletActionContext;   
  13.   
  14. import com.opensymphony.xwork2.ActionContext;   
  15. import com.opensymphony.xwork2.ActionSupport;   
  16.   
  17. public class IOUtilUpload extends ActionSupport {   
  18.   
  19.     private File image; //文件   
  20.     private String imageFileName; //文件名   
  21.     private String imageContentType;//文件类型   
  22.     public String execute(){   
  23.         try {     
  24.            if(image!=null){   
  25.                 //文件保存的父目录   
  26.                 String realPath=ServletActionContext.getServletContext()   
  27.                 .getRealPath("/image");   
  28.                 //要保存的新的文件名称   
  29.                 String targetFileName=generateFileName(imageFileName);   
  30.                 //利用父子目录穿件文件目录   
  31.                 File savefile=new File(new File(realPath),targetFileName);   
  32.                 if(!savefile.getParentFile().exists()){   
  33.                     savefile.getParentFile().mkdirs();   
  34.                 }   
  35.                 FileOutputStream fos=new FileOutputStream(savefile);   
  36.                 FileInputStream fis=new FileInputStream(image);   
  37.                    
  38.                 //如果复制文件的时候 出错了返回 值就是 -1 所以 初始化为 -2   
  39.                 Long result=-2L;   //大文件的上传   
  40.                 int  smresult=-2//小文件的上传   
  41.                    
  42.                 //如果文件大于 2GB   
  43.                 if(image.length()>1024*2*1024){   
  44.                     result=IOUtils.copyLarge(fis, fos);   
  45.                 }else{   
  46.                     smresult=IOUtils.copy(fis, fos);    
  47.                 }   
  48.                 if(result >-1 || smresult>-1){   
  49.                     ActionContext.getContext().put("message""上传成功!");   
  50.                 }   
  51.                 ActionContext.getContext().put("filePath", targetFileName);   
  52.            }   
  53.         } catch (Exception e) {     
  54.             e.printStackTrace();     
  55.         }     
  56.         return SUCCESS;     
  57.     }   
  58.        
  59.     /**  
  60.      * new文件名= 时间 + 全球唯一编号  
  61.      * @param fileName old文件名  
  62.      * @return new文件名  
  63.      */  
  64.     private String generateFileName(String fileName) {   
  65.         //时间   
  66.         DateFormat df = new SimpleDateFormat("yy_MM_dd_HH_mm_ss");      
  67.         String formatDate = df.format(new Date());   
  68.         //全球唯一编号   
  69.         String uuid=UUID.randomUUID().toString();   
  70.         int position = fileName.lastIndexOf(".");      
  71.         String extension = fileName.substring(position);      
  72.         return formatDate + uuid + extension;      
  73.     }   
  74. //get set   
  75. }  
package com.sh.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class IOUtilUpload extends ActionSupport {

	private File image; //文件
	private String imageFileName; //文件名
	private String imageContentType;//文件类型
	public String execute(){
		try {  
           if(image!=null){
				//文件保存的父目录
				String realPath=ServletActionContext.getServletContext()
				.getRealPath("/image");
				//要保存的新的文件名称
				String targetFileName=generateFileName(imageFileName);
				//利用父子目录穿件文件目录
				File savefile=new File(new File(realPath),targetFileName);
				if(!savefile.getParentFile().exists()){
					savefile.getParentFile().mkdirs();
				}
				FileOutputStream fos=new FileOutputStream(savefile);
				FileInputStream fis=new FileInputStream(image);
				
				//如果复制文件的时候 出错了返回 值就是 -1 所以 初始化为 -2
				Long result=-2L;   //大文件的上传
				int  smresult=-2; //小文件的上传
				
				//如果文件大于 2GB
				if(image.length()>1024*2*1024){
					result=IOUtils.copyLarge(fis, fos);
				}else{
					smresult=IOUtils.copy(fis, fos); 
				}
	            if(result >-1 || smresult>-1){
	            	ActionContext.getContext().put("message", "上传成功!");
	            }
	            ActionContext.getContext().put("filePath", targetFileName);
           }
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return SUCCESS;  
	}
	
	/**
	 * new文件名= 时间 + 全球唯一编号
	 * @param fileName old文件名
	 * @return new文件名
	 */
	private String generateFileName(String fileName) {
		//时间
        DateFormat df = new SimpleDateFormat("yy_MM_dd_HH_mm_ss");   
        String formatDate = df.format(new Date());
        //全球唯一编号
        String uuid=UUID.randomUUID().toString();
        int position = fileName.lastIndexOf(".");   
        String extension = fileName.substring(position);   
        return formatDate + uuid + extension;   
    }
//get set
}



struts.xml

Xml代码 复制代码 收藏代码
  1. <action name="iOUtilUpload" class="com.sh.action.IOUtilUpload">  
  2.             <result name="input">/ioutilupload.jsp</result>  
  3.             <result name="success">/iuuSuccess.jsp</result>  
  4.         </action>  
<action name="iOUtilUpload" class="com.sh.action.IOUtilUpload">
    		<result name="input">/ioutilupload.jsp</result>
    		<result name="success">/iuuSuccess.jsp</result>
    	</action>


ioutilupload.jsp

Html代码 复制代码 收藏代码
  1. <form action="${pageContext.request.contextPath }/iOUtilUpload.action"    
  2.     enctype="multipart/form-data" method="post">  
  3.         文件:<input type="file" name="image"/>  
  4.         <input type="submit" value="上传"/>  
  5.     </form>  
<form action="${pageContext.request.contextPath }/iOUtilUpload.action" 
    enctype="multipart/form-data" method="post">
    	文件:<input type="file" name="image"/>
    	<input type="submit" value="上传"/>
    </form>


iuuSuccess.jsp

Html代码 复制代码 收藏代码
  1. <body>  
  2.     <b>${message}</b>  
  3.         ${imageFileName}<br/>  
  4.     <img src="image/${filePath}"/>  
  5.   </body>  
<body>
    <b>${message}</b>
   		${imageFileName}<br/>
    <img src="image/${filePath}"/>
  </body>



案例:删除服务器上的文件

Java代码 复制代码 收藏代码
  1. /**  
  2.      * 从服务器上 删除文件  
  3.      * @param fileName 文件名  
  4.      * @return true: 从服务器上删除成功   false:否则失败  
  5.      */  
  6.     public boolean delFile(String fileName){   
  7.         File file=new File(fileName);   
  8.         if(file.exists()){   
  9.             return file.delete();   
  10.         }   
  11.         return false;   
  12.     }  
/**
	 * 从服务器上 删除文件
	 * @param fileName 文件名
	 * @return true: 从服务器上删除成功   false:否则失败
	 */
	public boolean delFile(String fileName){
		File file=new File(fileName);
		if(file.exists()){
			return file.delete();
		}
		return false;
	}



案例:使用数组上传多个文件
action.java

Java代码 复制代码 收藏代码
  1. package com.sh.action;   
  2.   
  3. import java.io.File;   
  4. import java.io.FileInputStream;   
  5. import java.io.FileOutputStream;   
  6. import java.util.Random;   
  7.   
  8. import org.apache.struts2.ServletActionContext;   
  9.   
  10. import com.opensymphony.xwork2.ActionContext;   
  11. import com.opensymphony.xwork2.ActionSupport;   
  12.   
  13. /**  
  14.  * @author Administrator  
  15.  *  
  16.  */  
  17. public class ArrayUpload extends ActionSupport {   
  18.   
  19.     private File[] image;   
  20.     private String[] imageContentType;   
  21.     private String[] imageFileName;   
  22.     private String path;   
  23.        
  24.     public String getPath() {   
  25.         return ServletActionContext.getRequest().getRealPath(path);   
  26.     }   
  27.   
  28.     public void setPath(String path) {   
  29.         this.path = path;   
  30.     }   
  31.   
  32.     @Override  
  33.     public String execute() throws Exception {   
  34.       for(int i=0;i<image.length;i++){   
  35.           imageFileName[i]=getFileName(imageFileName[i]);   
  36.           String targetFileName=getPath()+"\\"+imageFileName[i];   
  37.           FileOutputStream fos=new FileOutputStream(targetFileName);   
  38.           FileInputStream fis=new FileInputStream(image[i]);   
  39.           byte[] b=new byte[1024];   
  40.           int len=0;   
  41.           while ((len=fis.read(b))>0) {   
  42.             fos.write(b, 0, len);   
  43.         }   
  44.       }   
  45.       return SUCCESS;   
  46.     }   
  47.     private String getFileName(String fileName){   
  48.         int position=fileName.lastIndexOf(".");   
  49.         String extension=fileName.substring(position);   
  50.         int radom=new Random().nextInt(1000);   
  51.         return ""+System.currentTimeMillis()+radom+extension;   
  52.     }   
  53. //get set   
  54. }  
package com.sh.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Random;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @author Administrator
 *
 */
public class ArrayUpload extends ActionSupport {

	private File[] image;
	private String[] imageContentType;
	private String[] imageFileName;
	private String path;
	
	public String getPath() {
		return ServletActionContext.getRequest().getRealPath(path);
	}

	public void setPath(String path) {
		this.path = path;
	}

	@Override
	public String execute() throws Exception {
	  for(int i=0;i<image.length;i++){
		  imageFileName[i]=getFileName(imageFileName[i]);
		  String targetFileName=getPath()+"\\"+imageFileName[i];
		  FileOutputStream fos=new FileOutputStream(targetFileName);
		  FileInputStream fis=new FileInputStream(image[i]);
		  byte[] b=new byte[1024];
		  int len=0;
		  while ((len=fis.read(b))>0) {
			fos.write(b, 0, len);
		}
	  }
	  return SUCCESS;
	}
	private String getFileName(String fileName){
		int position=fileName.lastIndexOf(".");
		String extension=fileName.substring(position);
		int radom=new Random().nextInt(1000);
		return ""+System.currentTimeMillis()+radom+extension;
	}
//get set
}



struts.xml

Xml代码 复制代码 收藏代码
  1. <action name="arrayUpload" class="com.sh.action.ArrayUpload">  
  2.         <interceptor-ref name="fileUpload">  
  3.             <param name="allowedTypes">  
  4.                 image/x-png,image/gif,image/bmp,image/jpeg   
  5.             </param>  
  6.             <param name="maximumSize">10240000</param>  
  7.         </interceptor-ref>  
  8.         <interceptor-ref name="defaultStack"/>  
  9.         <param name="path">/image</param>  
  10.         <result name="success">/arraySuccess.jsp</result>  
  11.         <result name="input">/arrayupload.jsp</result>  
  12.     </action>  
	<action name="arrayUpload" class="com.sh.action.ArrayUpload">
    		<interceptor-ref name="fileUpload">
    			<param name="allowedTypes">
    				image/x-png,image/gif,image/bmp,image/jpeg
    			</param>
    			<param name="maximumSize">10240000</param>
    		</interceptor-ref>
    		<interceptor-ref name="defaultStack"/>
    		<param name="path">/image</param>
    		<result name="success">/arraySuccess.jsp</result>
    		<result name="input">/arrayupload.jsp</result>
    	</action>



arrayUpload.jsp

Html代码 复制代码 收藏代码
  1. <body>  
  2.    ===========多文件上传=================   
  3.     <form action="${pageContext.request.contextPath }/arrayUpload.action"    
  4.    enctype="multipart/form-data" method="post">  
  5.     文件1:<input type="file" name="image"/><br/>  
  6.     文件2:<input type="file" name="image"/><br/>  
  7.     文件3:<input type="file" name="image"/>  
  8.     <input type="submit" value="上传"/>  
  9.    </form>  
  10.  </body>  
 <body>
    ===========多文件上传=================
     <form action="${pageContext.request.contextPath }/arrayUpload.action" 
    enctype="multipart/form-data" method="post">
    	文件1:<input type="file" name="image"/><br/>
    	文件2:<input type="file" name="image"/><br/>
    	文件3:<input type="file" name="image"/>
    	<input type="submit" value="上传"/>
    </form>
  </body>


arraySuccess.jsp

Html代码 复制代码 收藏代码
  1. <body>  
  2.     <b>使用数组上传成功s:iterator</b>  
  3.     <s:iterator value="imageFileName" status="st">  
  4.         第<s:property value="#st.getIndex()+1"/>个图片:<br/>  
  5.         [img]image/<s:property value="imageFileName[#st.getIndex()][/img]"/>  
  6.     </s:iterator>  
  7.      <br/><b>使用数组上传成功c:foreach</b>  
  8.      <c:forEach var="fn" items="${imageFileName}" varStatus="st">  
  9.         第${st.index+1}个图片:<br/>  
  10.         <img src="image/${fn}"/>  
  11.      </c:forEach>  
  12.   </body>  
<body>
    <b>使用数组上传成功s:iterator</b>
    <s:iterator value="imageFileName" status="st">
    	第<s:property value="#st.getIndex()+1"/>个图片:<br/>
    	[img]image/<s:property value="imageFileName[#st.getIndex()][/img]"/>
    </s:iterator>
     <br/><b>使用数组上传成功c:foreach</b>
     <c:forEach var="fn" items="${imageFileName}" varStatus="st">
     	第${st.index+1}个图片:<br/>
     	<img src="image/${fn}"/>
     </c:forEach>
  </body>



案例:使用List上传多个文件
action.java

Java代码 复制代码 收藏代码
  1. package com.sh.action;   
  2.   
  3. import java.io.File;   
  4. import java.io.FileInputStream;   
  5. import java.io.FileOutputStream;   
  6. import java.util.List;   
  7. import java.util.Random;   
  8.   
  9. import javax.servlet.Servlet;   
  10.   
  11. import org.apache.struts2.ServletActionContext;   
  12.   
  13. import com.opensymphony.xwork2.ActionSupport;   
  14.   
  15. public class ListUpload extends ActionSupport {   
  16. private List<File> doc;   
  17. private List<String> docContentType;   
  18. private List<String> docFileName;   
  19. private String path;   
  20. @Override  
  21. public String execute() throws Exception {   
  22.     for(int i=0;i<doc.size();i++){   
  23.         docFileName.set(i, getFileName(docFileName.get(i)));   
  24.         FileOutputStream fos=new FileOutputStream(getPath()+"\\"+docFileName.get(i));   
  25.         File file=doc.get(i);   
  26.         FileInputStream fis=new FileInputStream(file);   
  27.         byte [] b=new byte[1024];   
  28.         int length=0;   
  29.         while((length=fis.read(b))>0){   
  30.             fos.write(b,0,length);   
  31.         }   
  32.     }   
  33.     return SUCCESS;   
  34. }   
  35.   
  36.   
  37. public String getFileName(String fileName){   
  38.     int position=fileName.lastIndexOf(".");   
  39.     String extension=fileName.substring(position);   
  40.     int radom=new Random().nextInt(1000);   
  41.     return ""+System.currentTimeMillis()+radom+extension;   
  42. }   
  43. public String getPath() {   
  44.     return ServletActionContext.getRequest().getRealPath(path);   
  45. }  
package com.sh.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Random;

import javax.servlet.Servlet;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class ListUpload extends ActionSupport {
private List<File> doc;
private List<String> docContentType;
private List<String> docFileName;
private String path;
@Override
public String execute() throws Exception {
	for(int i=0;i<doc.size();i++){
		docFileName.set(i, getFileName(docFileName.get(i)));
		FileOutputStream fos=new FileOutputStream(getPath()+"\\"+docFileName.get(i));
		File file=doc.get(i);
		FileInputStream fis=new FileInputStream(file);
		byte [] b=new byte[1024];
		int length=0;
		while((length=fis.read(b))>0){
			fos.write(b,0,length);
		}
	}
	return SUCCESS;
}


public String getFileName(String fileName){
	int position=fileName.lastIndexOf(".");
	String extension=fileName.substring(position);
	int radom=new Random().nextInt(1000);
	return ""+System.currentTimeMillis()+radom+extension;
}
public String getPath() {
	return ServletActionContext.getRequest().getRealPath(path);
}


strust.xml

Xml代码 复制代码 收藏代码
  1. <action name="listUpload" class="com.sh.action.ListUpload">  
  2.             <interceptor-ref name="fileUpload">  
  3.                 <param name="allowedTypes">  
  4.                     image/x-png,image/gif,image/bmp,image/jpeg   
  5.                 </param>  
  6.                 <param name="maximumSize">  
  7.                     10240000   
  8.                 </param>  
  9.             </interceptor-ref>  
  10.             <interceptor-ref name="defaultStack"/>  
  11.             <param name="path">/image</param>  
  12.             <result name="success">/listSuccess.jsp</result>  
  13.             <result name="input">/listupload.jsp</result>  
  14.         </action>  
<action name="listUpload" class="com.sh.action.ListUpload">
    		<interceptor-ref name="fileUpload">
    			<param name="allowedTypes">
    				image/x-png,image/gif,image/bmp,image/jpeg
    			</param>
    			<param name="maximumSize">
    				10240000
    			</param>
    		</interceptor-ref>
    		<interceptor-ref name="defaultStack"/>
    		<param name="path">/image</param>
    		<result name="success">/listSuccess.jsp</result>
    		<result name="input">/listupload.jsp</result>
    	</action>



listUpload.jsp

Html代码 复制代码 收藏代码
  1. <body>  
  2.     ===========List 多文件上传=================   
  3.      <form action="${pageContext.request.contextPath }/listUpload.action"    
  4.     enctype="multipart/form-data" method="post">  
  5.         文件1:<input type="file" name="doc"/><br/>  
  6.         文件2:<input type="file" name="doc"/><br/>  
  7.         文件3:<input type="file" name="doc"/>  
  8.         <input type="submit" value="上传"/>  
  9.     </form>  
  10.       
  11.      <s:fielderror/>  
  12.     <s:form action="listUpload" enctype="multipart/form-data">  
  13.     <s:file name="doc" label="选择上传的文件"/>  
  14.         <s:file name="doc" label="选择上传的文件"/>  
  15.         <s:file name="doc" label="选择上传的文件"/>  
  16.         <s:submit value="上传"/>  
  17.     </s:form>  
  18.         
  19.   </body>  
<body>
    ===========List 多文件上传=================
     <form action="${pageContext.request.contextPath }/listUpload.action" 
    enctype="multipart/form-data" method="post">
    	文件1:<input type="file" name="doc"/><br/>
    	文件2:<input type="file" name="doc"/><br/>
    	文件3:<input type="file" name="doc"/>
    	<input type="submit" value="上传"/>
    </form>
   
     <s:fielderror/>
    <s:form action="listUpload" enctype="multipart/form-data">
	<s:file name="doc" label="选择上传的文件"/>
    	<s:file name="doc" label="选择上传的文件"/>
    	<s:file name="doc" label="选择上传的文件"/>
    	<s:submit value="上传"/>
    </s:form>
     
  </body>



listSuccess.jsp

Html代码 复制代码 收藏代码
  1. <body>  
  2.     <h3>使用List上传多个文件 s:iterator显示</h3>  
  3.     <s:iterator value="docFileName" status="st">  
  4.         第<s:property value="#st.getIndex()+1"/>个图片:   
  5.         <br/>  
  6.         <img src="image/<s:property value="docFileName.get(#st.getIndex())"/>"/><br/>  
  7.     </s:iterator>  
  8.     <h3>使用List上传多个文件 c:foreach显示</h3>  
  9.     <c:forEach var="fn" items="${docFileName}" varStatus="st">  
  10.           第${st.index}个图片<br/>  
  11.          <img src="image/${fn}"/>  
  12.     </c:forEach>  
  13. </body>  
  <body>
   	<h3>使用List上传多个文件 s:iterator显示</h3>
   	<s:iterator value="docFileName" status="st">
   		第<s:property value="#st.getIndex()+1"/>个图片:
   		<br/>
   		<img src="image/<s:property value="docFileName.get(#st.getIndex())"/>"/><br/>
   	</s:iterator>
   	<h3>使用List上传多个文件 c:foreach显示</h3>
  	<c:forEach var="fn" items="${docFileName}" varStatus="st">
  		  第${st.index}个图片<br/>
  		 <img src="image/${fn}"/>
  	</c:forEach>
  </body>



案例:Struts2 文件下载

Java代码 复制代码 收藏代码
  1. Struts2支持文件下载,通过提供的stram结果类型来实现。指定stream结果类型是,还需要指定inputName参数,此参数表示输入流,作为文件下载入口。  
Struts2支持文件下载,通过提供的stram结果类型来实现。指定stream结果类型是,还需要指定inputName参数,此参数表示输入流,作为文件下载入口。


简单文件下载 不含中文附件名

Java代码 复制代码 收藏代码
  1. package com.sh.action;   
  2.   
  3. import java.io.InputStream;   
  4.   
  5. import org.apache.struts2.ServletActionContext;   
  6.   
  7. import com.opensymphony.xwork2.ActionSupport;   
  8.   
  9. public class MyDownload extends ActionSupport {   
  10.   
  11.     private String inputPath;   
  12.   
  13.     //注意这的  方法名 在struts.xml中要使用到的   
  14.     public InputStream getTargetFile() {   
  15.         System.out.println(inputPath);   
  16.         return ServletActionContext.getServletContext().getResourceAsStream(inputPath);   
  17.     }   
  18.        
  19.     public void setInputPath(String inputPath) {   
  20.         this.inputPath = inputPath;   
  21.     }   
  22.   
  23.     @Override  
  24.     public String execute() throws Exception {   
  25.         // TODO Auto-generated method stub   
  26.         return SUCCESS;   
  27.     }   
  28.        
  29.        
  30. }  
package com.sh.action;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class MyDownload extends ActionSupport {

	private String inputPath;

	//注意这的  方法名 在struts.xml中要使用到的
	public InputStream getTargetFile() {
		System.out.println(inputPath);
		return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
	}
	
	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return SUCCESS;
	}
	
	
}


Struts.xml

Xml代码 复制代码 收藏代码
  1. <action name="mydownload" class="com.sh.action.MyDownload">  
  2.             <!--给action中的属性赋初始值-->  
  3.         <param name="inputPath">/image/1347372060765110.jpg</param>  
  4. <!--给注意放回后的 type类型-->  
  5.         <result name="success" type="stream">  
  6.                       <!--要下载文件的类型-->  
  7.             <param name="contentType">image/jpeg</param>  
  8.                         <!--action文件输入流的方法 getTargetFile()-->  
  9.             <param name="inputName">targetFile</param>  
  10.                         <!--文件下载的处理方式 包括内联(inline)和附件(attachment)两种方式--->  
  11.             <param name="contentDisposition">attachment;filename="1347372060765110.jpg"</param>  
  12.                        <!---下载缓冲区的大小-->  
  13.             <param name="bufferSize">2048</param>  
  14.         </result>  
  15.     </action>  
	<action name="mydownload" class="com.sh.action.MyDownload">
             <!--给action中的属性赋初始值-->
    		<param name="inputPath">/image/1347372060765110.jpg</param>
 <!--给注意放回后的 type类型-->
    		<result name="success" type="stream">
                       <!--要下载文件的类型-->
    			<param name="contentType">image/jpeg</param>
                         <!--action文件输入流的方法 getTargetFile()-->
    			<param name="inputName">targetFile</param>
                         <!--文件下载的处理方式 包括内联(inline)和附件(attachment)两种方式--->
    			<param name="contentDisposition">attachment;filename="1347372060765110.jpg"</param>
                        <!---下载缓冲区的大小-->
    			<param name="bufferSize">2048</param>
    		</result>
    	</action>



down.jsp

Html代码 复制代码 收藏代码
  1. <body>  
  2.         <h3>Struts 2 的文件下载</h3> <br>  
  3.         <a href="mydownload.action">我要下载</a>  
  4. </body>  
  <body>
  		<h3>Struts 2 的文件下载</h3> <br>
  		<a href="mydownload.action">我要下载</a>
  </body>


在ie下 可以看到会打开一个 文件下载对话框 有 打开  保存 取消 按钮
google中 没有了

文件下载,支持中文附件名 
action

Java代码 复制代码 收藏代码
  1. package com.sh.action;   
  2.   
  3. import java.io.InputStream;   
  4.   
  5. import org.apache.struts2.ServletActionContext;   
  6.   
  7. import com.opensymphony.xwork2.ActionSupport;   
  8.   
  9. public class DownLoadAction extends ActionSupport {   
  10.   
  11.     private final String DOWNLOADPATH="/image/";   
  12.     private String fileName;   
  13.          
  14.         //这个方法 也得注意 struts.xml中也会用到   
  15.     public InputStream getDownLoadFile(){   
  16.         return ServletActionContext.getServletContext().getResourceAsStream(DOWNLOADPATH+fileName);   
  17.     }   
  18.     //转换文件名的方法 在strust.xml中会用到   
  19.     public String getDownLoadChineseFileName(){   
  20.         String chineseFileName=fileName;   
  21.         try {   
  22.             chineseFileName=new String(chineseFileName.getBytes(),"ISO-8859-1");   
  23.         } catch (Exception e) {   
  24.             e.printStackTrace();   
  25.         }   
  26.         return chineseFileName;   
  27.     }   
  28.     @Override  
  29.     public String execute() throws Exception {   
  30.         // TODO Auto-generated method stub   
  31.         return SUCCESS;   
  32.     }   
  33.   
  34.     public String getFileName() {   
  35.         return fileName;   
  36.     }   
  37.   
  38.     public void setFileName(String fileName) {   
  39.         this.fileName = fileName;   
  40.     }   
  41.        
  42. }  
package com.sh.action;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownLoadAction extends ActionSupport {

	private final String DOWNLOADPATH="/image/";
	private String fileName;
      
        //这个方法 也得注意 struts.xml中也会用到
	public InputStream getDownLoadFile(){
		return ServletActionContext.getServletContext().getResourceAsStream(DOWNLOADPATH+fileName);
	}
	//转换文件名的方法 在strust.xml中会用到
	public String getDownLoadChineseFileName(){
		String chineseFileName=fileName;
		try {
			chineseFileName=new String(chineseFileName.getBytes(),"ISO-8859-1");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return chineseFileName;
	}
	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return SUCCESS;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
}


struts.xml

Xml代码 复制代码 收藏代码
  1. <action name="download" class="com.sh.action.DownLoadAction">  
  2.             <param name="fileName">活动主题.jpg</param>  
  3.             <result name="success" type="stream">  
  4.                 <param name="contentType">image/jpeg</param>  
  5.                         <!-- getDownLoadFile() 这个方法--->  
  6.                 <param name="inputName">downLoadFile</param>  
  7.                 <param name="contentDisposition">attachment;filename="${downLoadChineseFileName}"</param>  
  8.                 <param name="bufferSize">2048</param>  
  9.             </result>  
  10.         </action>  
<action name="download" class="com.sh.action.DownLoadAction">
    		<param name="fileName">活动主题.jpg</param>
    		<result name="success" type="stream">
    			<param name="contentType">image/jpeg</param>
                        <!-- getDownLoadFile() 这个方法--->
    			<param name="inputName">downLoadFile</param>
    			<param name="contentDisposition">attachment;filename="${downLoadChineseFileName}"</param>
    			<param name="bufferSize">2048</param>
    		</result>
    	</action>


down1.jsp

Html代码 复制代码 收藏代码
  1. <body>  
  2.         <h3>Struts 2 的文件下载</h3> <br>  
  3.         <a href="download.action">我要下载</a>  
  4.   </body>  
posted on 2013-09-23 21:09  zs453898875  阅读(220)  评论(0)    收藏  举报