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

文件的上传与下载

上传

Servlet3.0的上传改进

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

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

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

表单属性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()+"
"); out.println("上传文件的大小"+part.getSize()+"
"); Collection headerNames=part.getHeaderNames(); for(String headerName:headerNames){ out.println(headerName+"-->"+part.getHeader(headerName)+"
"); } // 这里 路径为绝对路径 / 表示 的是 webroot 的 根路径 part.write(getServletContext().getRealPath("/uploadFiles")+"/"+fileName); } }

index.jsp

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




  
    
    My JSP 'index.jsp' starting page
	
  
  
  
   
文件名: 文件:

web.xml



  upload2
  
  
  upload
  action.uploadServlet
  
  
  upload
  /uploadServlet
  
  
    
    index.jsp
   
  


运行方式及结果

struts2入门教程三(上传与下载)_第1张图片
struts2入门教程三(上传与下载)_第2张图片

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




 
	
		
		/uploadFiles
			
				/succ.jsp
			
			/login.jsp
		
	
	

成功页面

succ.jsp

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



  
    
    My JSP 'index.jsp' starting page
	
  
  
  
  
  <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
   上传成功!
文件标题:
文件为:"/>

index.jsp

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




  
    
    My JSP 'index.jsp' starting page
	
  
  
  
   
文件名: 文件:

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



  
  
	
		

			/uploadFiles

			image/png,image/gif,image/jpg,image/jpeg
			
				/succ.jsp
			
			/index.jsp

			
			
				
				image/png,image/gif,image/jpeg
				
				2000
			
			
			

		
	



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



  
    
    My JSP 'index.jsp' starting page
	
  
  
  
  
   
文件名:
文件:

文件名:
文件:

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



  
	
		

			/uploadFiles

			image/png,image/gif,image/jpg,image/jpeg
			
				/succ.jsp
			
			/index.jsp
		
	


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



  
    
    My JSP 'index.jsp' starting page
	
  
  
  
  
   
文件名:
文件:

文件名:
文件:

下载

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

		\uploadFiles\扑克.png
		
		
		image/png
		targetFile
		4096
		filename="1110.jpg"
		
		
		/index.jsp
		
		

下载页面
简单的超链接下载
111
222


简单的超链接下载

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



你可能感兴趣的:(struts2)