Struts2 文件上传与下载

 
 

上传  控制层代码

package cn.yunhe.struts.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.yunhe.struts.model.UserModel;

public class UserController extends ActionSupport implements ModelDriven<Object>{
	
	private static final long serialVersionUID = 1L;
	
	private UserModel um;
	
	/**
	 * 账户名称
	 */
	private String username;
	
	/**
	 * 用户头像
	 * 
	 * file并不是指前端JSP上传过来的文件本身,而是文件上传过来存放在临时文件夹下面的文件
	 */
	private File userhead;
	
	/**
	 * 用户头像文件名
	 * 提交过来的file的名字[文件名FileName]
	 */
	private String userheadFileName;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public File getUserhead() {
		return userhead;
	}
	public void setUserhead(File userhead) {
		this.userhead = userhead;
	}
	public String getUserheadFileName() {
		return userheadFileName;	
	}
	public void setUserheadFileName(String userheadFileName) {
		this.userheadFileName = userheadFileName;
	}
	public void uploadFile() throws IOException{
		
		
		System.out.println("um.getNickname():"+um.getNickname());
				//保存上传文件的路径
		String root = ServletActionContext.getServletContext().getRealPath("/upload");
		
		 //获取临时文件输入流
        InputStream is = new FileInputStream(userhead);
        
        System.out.println(root);
        System.out.println(userheadFileName);
        
        //输出文件
        OutputStream os = new FileOutputStream(new File(root, userheadFileName));
        //打印出上传的文件的文件名
        System.out.println("fileFileName: " + userheadFileName);
        //因为file是存放在临时文件夹的文件,我们可以将其文件名和文件路径打印出来,看和之前的fileFileName是否相同
        System.out.println("file: " + userhead.getName());
        System.out.println("file: " + userhead.getPath());

        byte[] buffer = new byte[1024];
        int len = 0;
        //循环,从输入流中每次读取buffer大小的字节数组到buffer字节数组中,read返回值为读取到的字节数组的真实大小,并赋值给len变量
        //如果读取到文件的结尾则会read返回-1赋值给len变量
        while((len = is.read(buffer))!=-1){
        	System.out.println("len:"+len);
        	//将每次读取的字节数据(从第0位到第len位),写入到文件输出流中
            os.write(buffer,0,len);
        }

        os.close();
        is.close();
	}
	
	
	public UserModel getModel() {
		if(um==null){
			um = new UserModel();
			um.setUsername("zhagnsan");
			um.setNickname("nihao");	
		}
		return um;
	}
	
}

上传页面代码

<!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">
<script type="text/javascript" src="layui/layui.js"></script>
<link  rel="stylesheet" href="layui/css/layui.css"  media="all" >
<title>Insert title here</title>
</head>

<script type="text/javascript">
    
</script>
<body>
 	
 	<form class="layui-form layui-form-pane"  method="post"  action="/user/user101" enctype="multipart/form-data" >
 	<div class="layui-form-item">
 	<label class="layui-form-label">用户名:</label>
    <div class="layui-input-block">
      <input type="text" name="title"  placeholder="请输入用户名" class="layui-input">
    </div>
 	</div>
 	
 	<div class="layui-form-item">
 		<label class="layui-form-label">用户头像:</label>
 		<div class="layui-input-block">
 		<input type="file" name="userhead"    >
 		<input type="submit"  value="提交"  class="layui-btn layui-btn-normal">
 	</div>
 	
 	</div>
 	
	</form>
</body>
</html>

配置文件:

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>

	<package name="yunhe-user" namespace="/user" extends="struts-default">
	
		<interceptors>
			<interceptor name="cslanjie" class="cn.yunhe.struts.interceptor.CeshiInterceptor"></interceptor>
		</interceptors>
		
		
		<action name="upload" class="cn.yunhe.struts.controller.UserController" method="uploadFile">
		
			<!-- 传文件拦截器必须得用ActionSupport -->
			<interceptor-ref name="fileUpload">
				<!-- 单位是字节bytes(*号不能写,代表正则表达式匹配所有) -->
				<param name="maximumSize">10240000000000</param>
				<param name="allowedTypes">image/bmp,image/jpg,image/jpeg,image/png,image/gif,image/pjepg</param>
				<param name="allowedExtensions">png,bmp,jpg,jpeg,gif</param>
			</interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
			<!-- 如果文件上传类型错误或者文件大小不满足,自动跳转到input类型结果,此name为struts约定的固定名字 -->
			<result name="input">/index.jsp</result>
		</action>
		
		<action name="download" class="cn.yunhe.struts.controller.DownController">
 			<result name="success" type="stream"> 
 				<param name="contentDisposition">attachment;filename="${fileName}"</param>
 				<param name="inputName">ab</param>
 			</result>
		</action>
	</package>

</struts>

下载控制层代码:

package cn.yunhe.struts.controller;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DownController extends ActionSupport {

	private static final long serialVersionUID = 1L;
	// 要下载文件在服务器上的路径
	private String fileid;
	// 要下载文件的文件名
	private String fileName;

	public String getFileid() {
		return fileid;
	}

	public void setFileid(String fileid) {
		this.fileid = fileid;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public String getFileName() {
		return fileName;
	}

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

	public InputStream getAb() {
		
		//TODO:根据fileid去数据库查询对应的用户上传的原始文件名filename
		//TODO:以下为模拟数据
		Map<String,String> fileMap = new HashMap<String,String>();
		fileMap.put("10010", "zhangsan.jpg");
		fileMap.put("10012", "lisi.png");
		

		this.fileName = fileMap.get(fileid);
		
		return ServletActionContext.getServletContext().getResourceAsStream("/upload/" + "222222.png");
	}

	public String execute() throws Exception {
		return SUCCESS;
	}

}

下载页面:


<!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="http://127.0.0.1:8080/upload/Hydrangeas.jpg">点击下载     图 片1</a>
	<a href="http://127.0.0.1:8080/user/down?fileid=10012">点击下载  图片2</a>
</body>
</html>




你可能感兴趣的:(Struts2 文件上传与下载)