struts2入门教程三(上传与下载)

文件的上传与下载

上传

Servlet3.0的上传改进

HttpServletRequest增加了对文件上传的支持

Part getPart(String name)通过名称获取文件上传域

Collection<Part> getParts() 获取所有文件上传域

<input type="file".../>

表单属性enctype,数据表单编码方式

application/x-www-form0urlencoded

multipart/form-data

text/plain

java 代码
package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@MultipartConfig
public class uploadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/html;charset=UTF-8");
		
		PrintWriter out=response.getWriter();
		String fileName=request.getParameter("name");
		Part part=request.getPart("file");
		
		out.println("上传文件的类型:"+part.getContentType()+"<br/>");
		out.println("上传文件的大小"+part.getSize()+"<br/>");
		Collection<String> headerNames=part.getHeaderNames();
		 for(String headerName:headerNames){
			 out.println(headerName+"-->"+part.getHeader(headerName)+"<br/>");
			 
		 }
		 //  这里 路径为绝对路径 / 表示 的是 webroot 的 根路径
		 part.write(getServletContext().getRealPath("/uploadFiles")+"/"+fileName);
	}

}

index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'index.jsp' starting page</title>
	
  </head>
  
  <body>
   <form action="/upload2/uploadServlet" method="post" enctype="multipart/form-data">
 文件名:<input type="text" name="name">
 文件:<input type="file" name="file">
 <input type="submit">
</form>
  </body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>upload2</display-name>
  
  <servlet>
  <servlet-name>upload</servlet-name>
  <servlet-class>action.uploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>upload</servlet-name>
  <url-pattern>/uploadServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    
    <welcome-file>index.jsp</welcome-file>
   
  </welcome-file-list>
</web-app>

运行方式及结果


struts2单文件上传

java代码
package 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 UploadAction extends ActionSupport {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String title;
	private File upload;
	private String uploadContentType;
	private String uploadFileName;
	private String savePath;
	
	public String upload()throws Exception{
		FileInputStream fis=new FileInputStream(getUpload());
		FileOutputStream fos=new FileOutputStream(getSavePath()+"\\"+getUploadFileName());
		byte[] buffer=new byte[1024];
		int len=0;
		while((len=fis.read(buffer))>0){
			fos.write(buffer,0,len);
		}
		
		fos.close();
		fis.close();
		
		return SUCCESS;
		
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getSavePath() {
		// 返回 绝对路径
		return ServletActionContext.getServletContext().getRealPath(savePath);
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	
	
	
	
}
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>
 
	<package name="hello" namespace="/hello" extends="struts-default">
		<action name="upload" class="action.UploadAction" method="upload">
		<param name="savePath">/uploadFiles</param>
			<result name="success">
				/succ.jsp
			</result>
			<result name="input">/login.jsp</result>
		</action>
	</package>
	
</struts>
成功页面
succ.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags"  prefix="s"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'index.jsp' starting page</title>
	
  </head>
  
  <body>
  
  <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
   上传成功!<br/>
	文件标题:<s:property value=" + title"/><br/>
	文件为:<img src="<%=basePath %><s:property value="'uploadFiles/' 
		+ uploadFileName"/>"/><br/>
  </body>

</html>

index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'index.jsp' starting page</title>
	
  </head>
  
  <body>
   <form action="hello/upload" method="post" enctype="multipart/form-data">
 文件名:<input type="text" name="title">
 文件:<input type="file" name="upload">
 <input type="submit">
</form>
  </body>

</html>

Struts 多文件上传

一:使用struts2自身的验证
java 代码
package 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 UploadAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String[] titles;
	private File[] upload;
	private String[] uploadContentType;
	private String[] uploadFileName;
	private String savePath;
    private String allowTypes;
	
	public String upload() throws Exception {

		if (upload.length <= 0) {
			return null;
		}

		for (int i = 0; i < upload.length; i++) {

			FileInputStream fis = new FileInputStream(getUpload()[i]);
			System.out.println(getUploadFileName());
			FileOutputStream fos = new FileOutputStream(getSavePath() + "\\"
					+ getUploadFileName()[i]);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}

			fos.close();
			fis.close();
		}

		return SUCCESS;

	}
	
	
	public boolean check(String type){
		String[] types=allowTypes.split(",");
		
		for (String s: types) {
			if(s.equals(type)){
				return true;
			}
		}
		
		return false;
	}
	
//	public void validate(){
//		
//		for (String Type : uploadContentType) {
//			
//			boolean b=check(Type);
//			
//			if(!b){
//				// 添加FieldError
//				addFieldError("upload", "您要上传的文件类型不正确!");			}
//		}
//		
//	}
//	

	public String[] getTitles() {
		return titles;
	}

	public void setTitles(String[] titles) {
		this.titles = titles;
	}

	public File[] getUpload() {
		return upload;
	}

	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	public String[] getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String[] getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath(savePath);
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	// 设计校验类型的 注入
	public void setAllowTypes(String allowTypes) {
		this.allowTypes = allowTypes;
	}

	
	
	
	/*
	 * // 返回 绝对路径 return
	 * ServletActionContext.getServletContext().getRealPath(savePath);
	 */
}

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="mess"/>
  <constant name="struts.i18n.resources" value="UTF-8"/>
	<package name="hello" namespace="/hello" extends="struts-default">
		<action name="upload" class="action.UploadAction" method="upload">

			<param name="savePath">/uploadFiles</param>

			<param name="allowTypes">image/png,image/gif,image/jpg,image/jpeg</param>
			<result name="success">
				/succ.jsp
			</result>
			<result name="input">/index.jsp</result>

			<!-- 配置fileUpload的拦截器 -->
			<interceptor-ref name="fileUpload">
				<!-- 配置允许上传的文件类型 -->
				<param name="allowedTypes">image/png,image/gif,image/jpeg</param>
				<!-- 配置允许上传的文件大小 -->
				<param name="maximumSize">2000</param>
			</interceptor-ref>
			<!--  配置系统默认的拦截器 -->
			<interceptor-ref name="defaultStack"></interceptor-ref>

		</action>
	</package>

</struts>

index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'index.jsp' starting page</title>
	
  </head>
  
  <body>
  <s:fielderror/>
   <form action="hello/upload" method="post" enctype="multipart/form-data">
 文件名:<input type="text" name="titles"><br/>
 文件:<input type="file" name="upload"><br/><br/>
 文件名:<input type="text" name="titles"><br/>
 文件:<input type="file" name="upload"><br/>
 <input type="submit" value="上传">
</form>
  </body>
</html>

mess.properties---国际化的实现
struts.messages.error.file.too.large=\u4E0A\u4F20\u7684\u6587\u4EF6\u592A\u5927\u8D85\u8FC7\u89C4\u5B9A\u9650\u5236
struts.messages.error.content.type.not.allowed=\u4E0A\u4F20\u7684\u6587\u4EF6\u7C7B\u578B\u4E0D\u5141\u8BB8
struts.messages.error.uploading=\u4E0A\u4F20\u9519\u8BEF

 二: 使用自定义的方式验证
java 代码
package 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 UploadAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String[] titles;
	private File[] upload;
	private String[] uploadContentType;
	private String[] uploadFileName;
	private String savePath;
    private String allowTypes;
	
	public String upload() throws Exception {

		if (upload.length <= 0) {
			return null;
		}

		for (int i = 0; i < upload.length; i++) {

			FileInputStream fis = new FileInputStream(getUpload()[i]);
			System.out.println(getUploadFileName());
			FileOutputStream fos = new FileOutputStream(getSavePath() + "\\"
					+ getUploadFileName()[i]);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}

			fos.close();
			fis.close();
		}

		return SUCCESS;

	}
	
	
	public boolean check(String type){
		String[] types=allowTypes.split(",");
		
		for (String s: types) {
			if(s.equals(type)){
				return true;
			}
		}
		
		return false;
	}
	
	public void validate(){
	
		for (String Type : uploadContentType) {
			
			boolean b=check(Type);
		
		if(!b){
			// 添加FieldError
			addFieldError("upload", "您要上传的文件类型不正确!");			}
		}
		
	}
	

	public String[] getTitles() {
		return titles;
	}

	public void setTitles(String[] titles) {
		this.titles = titles;
	}

	public File[] getUpload() {
		return upload;
	}

	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	public String[] getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String[] getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath(savePath);
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	// 设计校验类型的 注入
	public void setAllowTypes(String allowTypes) {
		this.allowTypes = allowTypes;
	}

}

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>
  
	<package name="hello" namespace="/hello" extends="struts-default">
		<action name="upload" class="action.UploadAction" method="upload">

			<param name="savePath">/uploadFiles</param>

			<param name="allowTypes">image/png,image/gif,image/jpg,image/jpeg</param>
			<result name="success">
				/succ.jsp
			</result>
			<result name="input">/index.jsp</result>
		</action>
	</package>

</struts>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'index.jsp' starting page</title>
	
  </head>
  
  <body>
  <s:fielderror/>
   <form action="hello/upload" method="post" enctype="multipart/form-data">
 文件名:<input type="text" name="titles"><br/>
 文件:<input type="file" name="upload"><br/><br/>
 文件名:<input type="text" name="titles"><br/>
 文件:<input type="file" name="upload"><br/>
 <input type="submit" value="上传">
</form>
  </body>
</html>

下载

struts的下载方式

struts2 的文件下载
java 代码
package action;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownAction extends ActionSupport {

	//该属性可以在配置文件中动态指定该属性值
		private String inputPath;
		//依赖注入该属性值的setter方法
		public void setInputPath(String value)
		{
			inputPath = value;
		}
		/*
		定义一个返回InputStream的方法,
		该方法将作为被下载文件的入口,
		且需要配置stream类型结果时指定inputName参数,
		inputName参数的值就是方法去掉get前缀、首字母小写的字符串
		*/
		public InputStream getTargetFile() throws Exception 
		{
			//ServletContext提供getResourceAsStream()方法
			//返回指定文件对应的输入流 
			return ServletActionContext.getServletContext()
				.getResourceAsStream(inputPath);
		}
	
}

struts.xml
配置一个action
<action name="down" class="action.DownAction">
		<param name="inputPath">\uploadFiles\扑克.png</param>
		
		<result name="success" type="stream">
		<param name="contentType">image/png</param>
		<param name="inputName">targetFile</param>
		<param name="bufferSize">4096</param>
		<param name="contentDisposition">filename="1110.jpg"</param>
		</result>
		<result name="input">
		/index.jsp
		</result>
		</action>

下载页面
简单的超链接下载
<a href="hello/down">111</a>
<a href="hello/down">222</a>
<!-- <a href="uploadFiles/15.jpg">111</a>
<a href="uploadFiles/扑克.png">222</a> -->

简单的超链接下载

只需要基本的一个访问链接即可



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值