Strus2_文件的上传与下载

文件的上传


表单的准备
要想使用HTML表单上传一个或多个文件
--须把HTML表单的enctype属性设置为multipart/form-data
--须把HTML表单的method属性设置为post
--需添加<input type="file">字段


1.
1)表单需要注意的3点
2)Struts2的文件上传实际上使用的是Commons FileUpload组建,所以需要导入
common-fileupload-1.3.jar
common-io-2.0.1.jar
3)Struts2进行文件上传需要使用FileUpload拦截器
4)基本的文件上传:直接在A抽屉on中定义如下3个属性,并提供对应的get和set方法
//文件对应的File对象
private File [fileFieldName];
//文件类型
private String [fileFieldName]ContentType;
//文件名
private String [fileFieldName]FileName;
5)使用IO流进行文件的上传即可
6)一次传多个文件怎么办?
若传递多个文件,则上述的三个属性可以改为list类型


7)可以对上传的文件进行限制吗?例如拓展名,内容类型,上传文件的大小?若可以,则若出错,显示什么错误消息呢?消息可以定制吗?
可以的
可以通过配置FileUploadInterceptor拦截器的参数的方式来进行限制
maximumSize (optional)-默认的最大值为2M,上传的单个文件的最大值
allowedTypes (optional)-允许的上传文件的类型,多个使用逗号分割
allowedExtensions (optional)-允许的上传文件的拓展名,多个使用逗号分割
注意:org.apache.struts2下的default.properties有定义以上参数

定制错误消息,可以在国际化资源文件中定义如下的消息:
struts.messages.error.uploading-文件上传出错的消息
struts.messages.error.file.too.large-文件上传超过最大值的消息
struts.messages.error.content.type.not.allowed-文件内容类型不合法的消息
struts.messages.error.file.extension.not.allowed-文件拓展名不合法的消息


问题:此种方式定制的消息并不完善,可以参考org.apache.struts2下的struts-messages.properties,可以提供更多的定制消息




文件的下载


概述

在某些应用程序里,可能需要动态的把一个文件发送到用户的浏览器中,而这个文件的名字和存放位置在编程时是无法预知的。

文件的下载
1.Struts2中使用type="stream"的result进行下载即可
2.具体使用细节参看struts-2.3.28.1-all/struts-2.3.28.1/docs/docs/home.html
3.Stream结果类型
Struts专门为文件下载提供了一种Stream结果类型,在使用一个Stream结果时,不必准备一个jsp页面。
Stream结果类型可以设置如下参数:
--contentType:被下载的文件的MIME类型,默认值为text/plain
--contentLength:被下载的文件的大小,以字节为单位
--contentDisposition:可以设置下载文件名的ContentDisposition响应头,默认值为inline,通常设置为如下格式:attachment;filename="document.pdf"
--inputName:Action中提供的文件的输入流,指文件输入流的getter定义的那个属性的名字,默认值为inputStream
--bufferSize:文件下载时缓冲区的大小,默认值为1024
--alloweCaching:文件下载时是否允许使用缓存,默认值为true
--contentCharSet: 文件下载时的字符编码。
Stream结果类型的参数可以在Action以属性的方式覆盖,即以上参数可以在Action中以getter方法的方式提供。

范例

Strus2_文件的上传与下载_第1张图片

struts.xml

<?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.custom.i18n.resources" value="i18n"></constant> 

    <package name="default" namespace="/" extends="struts-default">
    	
    	<interceptors>
    		<interceptor-stack name="wulStack">
    			<interceptor-ref name="defaultStack">
    				<param name="fileUpload.maximumSize">20</param>
    				<param name="fileUpload.allowedTypes">text/html,text/xml,text/plain
    				</param>
    				<param name="fileUpload.allowedExtensions">html,txt,xml</param>
    			</interceptor-ref>
    		</interceptor-stack>
    	</interceptors>
    	
    	<default-interceptor-ref name="wulStack"></default-interceptor-ref>
    
		<action name="testUpload" class="com.wul.app.action.UploadAction">
			<result>/success.jsp</result>
			
		</action>
		
		<action name="testUpload2" class="com.wul.app.action.UploadAction2">
			<result name="success">/success.jsp</result>
			<result name="input">/upload2.jsp</result>
		</action>
		
		<action name="testDownload" class="com.wul.app.action.DownloadAction">
	 		<result type="stream">
	 			<param name="bufferSize">2048</param>
	 		</result>
	 	</action>
 
    </package>



</struts>
i18n.properties
#struts.messages.error.uploading=\u6587\u4EF6\u4E0A\u4F20\u51FA\u9519\u7684\u6D88\u606F
#struts.messages.error.file.too.large=\u6587\u4EF6\u4E0A\u4F20\u8D85\u8FC7\u6700\u5927\u503C\u7684\u6D88\u606F
#struts.messages.error.content.type.not.allowed=\u6587\u4EF6\u5185\u5BB9\u7C7B\u578B\u4E0D\u5408\u6CD5\u7684\u6D88\u606F
#struts.messages.error.file.extension.not.allowed=\u6587\u4EF6\u62D3\u5C55\u540D\u4E0D\u5408\u6CD5\u7684\u6D88\u606F
struts.messages.error.uploading=Error uploading: {0}
struts.messages.error.file.too.large=File {0} is too large to be uploaded. Maximum allowed size is {4} bytes!
struts.messages.error.content.type.not.allowed=Content-Type not allowed: {0} "{1}" "{2}" {3}
struts.messages.error.file.extension.not.allowed=File extension not allowed: {0} "{1}" "{2}" {3}
UploadAction.java

package com.wul.app.action;

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

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private File ppt;
	private String pptContentType;
	private String pptFileName;
	private String pptDesc;
	
	
	public String getPptDesc() {
		return pptDesc;
	}
	public void setPptDesc(String pptDesc) {
		this.pptDesc = pptDesc;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	public String getPptContentType() {
		return pptContentType;
	}
	public void setPptContentType(String pptContentType) {
		this.pptContentType = pptContentType;
	}
	public String getPptFileName() {
		return pptFileName;
	}
	public void setPptFileName(String pptFileName) {
		this.pptFileName = pptFileName;
	}
	
	
	
	public File getPpt() {
		return ppt;
	}
	public void setPpt(File ppt) {
		this.ppt = ppt;
	}
	@Override
	public String execute() throws Exception {	
		System.out.println(ppt);
		System.out.println(pptContentType);
		System.out.println(pptFileName);
		System.out.println(pptDesc);
		
		ServletContext servletContext = ServletActionContext.getServletContext();
		String dir = servletContext.getRealPath("/files/"+pptFileName);
		System.out.println(dir);
		
		FileOutputStream out = new FileOutputStream(dir);
		FileInputStream in = new FileInputStream(ppt);
		
		byte[] buffer = new byte[1024];
		int len=0;
		
		while((len = in.read(buffer)) != -1){
			out.write(buffer,0,len);
		}
		out.close();
		in.close();
		
		return SUCCESS;
	}

}
UploadAction2.java

package com.wul.app.action;

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

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction2 extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private List<File> file;
	private List<String> fileContentType;
	private List<String> fileFileName;
	private List<String> fileDesc;
	
	
	

	public List<File> getFile() {
		return file;
	}




	public void setFile(List<File> file) {
		this.file = file;
	}




	public List<String> getFileContentType() {
		return fileContentType;
	}




	public void setFileContentType(List<String> fileContentType) {
		this.fileContentType = fileContentType;
	}




	public List<String> getFileFileName() {
		return fileFileName;
	}




	public void setFileFileName(List<String> fileFileName) {
		this.fileFileName = fileFileName;
	}




	public List<String> getFileDesc() {
		return fileDesc;
	}




	public void setFileDesc(List<String> fileDesc) {
		this.fileDesc = fileDesc;
	}




	@Override
	public String execute() throws Exception {	
		System.out.println(file);
		System.out.println(fileContentType);
		System.out.println(fileFileName);
		System.out.println(fileDesc);
		
		
		return SUCCESS;
	}

}




<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">DownloadAction.java</span>

package com.wul.app.action;

import java.io.FileInputStream;
import java.io.InputStream;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownloadAction extends ActionSupport{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private String contentType;
	private long contentLength;
	private String contentDisposition;
	
	private InputStream inputStream;
	
	public InputStream getInputStream() {
		return inputStream;
	}
	
	public String getContentType() {
		return contentType;
	}



	public void setContentType(String contentType) {
		this.contentType = contentType;
	}



	public long getContentLength() {
		return contentLength;
	}



	public void setContentLength(long contentLength) {
		this.contentLength = contentLength;
	}



	public String getContentDisposition() {
		return contentDisposition;
	}



	public void setContentDisposition(String contentDisposition) {
		this.contentDisposition = contentDisposition;
	}



	@Override
	public String execute() throws Exception {
		
		//确定各个成员变量的值
		contentType = "text/html";
		contentDisposition = "attachment;filename=home.html";
		
		ServletContext  servletContext = ServletActionContext.getServletContext();
		String fileName = servletContext.getRealPath("/files/home.html");
		inputStream = new FileInputStream(fileName);
		contentLength = inputStream.available();
		
		return SUCCESS;
	}
	
}
upload.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="s"  uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
		
		<s:form action="testUpload" method="post" enctype="multipart/form-data">
			<s:file name="ppt" label="PPTFILE"></s:file>
			<s:textfield name="pptDesc" label="PPTDesc"></s:textfield>
			
			<s:submit></s:submit>
			
		</s:form>
</body>
</html>
upload2.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="s"  uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
		<!-- 
		<s:form action="testUpload2" method="post" enctype="multipart/form-data">
			<s:file name="file" label="PPTFILE"></s:file>
			<s:textfield name="fileDesc[0]" label="fileDesc"></s:textfield>
			<s:file name="file" label="PPTFILE"></s:file>
			<s:textfield name="fileDesc[1]" label="fileDesc"></s:textfield>
			<s:file name="file" label="PPTFILE"></s:file>
			<s:textfield name="fileDesc[2]" label="fileDesc"></s:textfield>
			
			<s:submit></s:submit>
			
		</s:form> 
		-->
		
		<s:debug></s:debug>
		
		<s:form action="testUpload2" method="post" enctype="multipart/form-data" theme="simple">
			<s:fielderror name="file"></s:fielderror>
			PPTFILE:<s:file name="file"></s:file>
			<br><br>
			PPTDesc:<s:textfield name="fileDesc[0]" ></s:textfield>
			<br><br>
			
			PPTFILE:<s:file name="file" ></s:file>
			<br><br>
			PPTDesc:<s:textfield name="fileDesc[1]"></s:textfield>
			<br><br>
			
			<s:submit></s:submit>
			
		</s:form>
</body>
</html>
download.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="s"  uri="/struts-tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
		<a href="testDownload">下载</a>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="s"  uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
		success
</body>
</html>









你可能感兴趣的:(文件上传,struts,下载,实例,struts2.0)