Struts框架上传下载文件辅助类,简单实现Struts上传图片以及下载

       首先在看这篇文章的前提下,你得会用Struts框架,有一定的基础了解,说白了了解怎么搭建就行了,然后基本就能顺利运行本篇文章的Demo,当然这个类不仅仅局限于图片上传下载的,因为是自己用流写的方法所以可以支持其他文件上传下载。

       首先是给子控制器提供所需要的request属性以及结果码等的辅助类。

package com.yiang.strutsUtil;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

public class BaseAction implements ServletRequestAware, ServletResponseAware {

	// 一些必须的属性 拿到request的一些属性
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;
	protected ServletContext application;

	// 每一个action里方法处理完返回的结果码
	protected final String SUCCESS = "success";// 处理成功
	protected final String FAIL = "fail";// 或失败
	protected final String LIST = "list";// 查询所有的结果码
	protected final String PREADD = "preAdd";// 去增加界面结果码
	protected final String PREUPDATE = "preupdate";// 去修改界面结果码
	protected final String TOLIST = "tolist";// 增删改返回进去的结果码

	// 返回的结果集
	protected Object result;
	protected Object msg;
	protected int code;

        //封装
	public Object getResult() {
		return result;
	}

	public void setResult(Object result) {
		this.result = result;
	}

	public Object getMsg() {
		return msg;
	}

	public void setMsg(Object msg) {
		this.msg = msg;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		// TODO Auto-generated method stub
		this.response = response;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		// TODO Auto-generated method stub
		this.request = request;
		this.session = request.getSession();
		this.application = request.getServletContext();
	}

}

然后是实现功能的子控制器的代码

package com.yiang.three;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import com.yiang.strutsUtil.BaseAction;

public class FileAction extends BaseAction {

	/**
	 * 从前端页面传过来的文件 文件名.文件后缀
	 */
	private File file;
	/**
	 * 文件类型
	 */
	private String fileContentType;
	/**
	 * 文件名
	 */
	private String fileFileName;

	/**
	 * 虚拟路径
	 */
	private String virtualPath = File.separator + "upload";

	/**
	 * 上传文件
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	public String uploadFile() {
		System.out.println("文件名:" + fileFileName);
		System.out.println("文件类型:" + fileContentType);
		String realPath = getRealPath(virtualPath + File.separator + fileFileName);
		System.out.println("真实路径:" + realPath);
		try {
                        //这里是fileUtils要导入一个架包
                        //当然你可以根据下面当前类的copyFile来写一个同名不同参数的方法来实现
                        //因为这里提供架包下载是需要积分的,方法比较简单。我就不赚这个积分了。
			FileUtils.copyFile(file, new File(realPath));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 下载文件
	 * 
	 * @return
	 */
	public void downloadFile() {
		// 拿到对应的文件名以及文件类型
                //当然这里是模拟数据库拿出的形式来写的
		String fileName = "doupo.jpg";
		String fileType = "image" + File.separator + "jpg";
		response.setContentType(fileType);
		// 下载设置请求头需要attachment参数 
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		String realPath = getRealPath(virtualPath + File.separator + fileName);
		try {
			FileUtils.copyFile(new File(realPath), response.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 打开文件
	 * 
	 * @return
	 * @throws IOException
	 */
	public void openFile() {
		// 拿到对应的文件名以及文件类型
		String fileName = "doupo.jpg";
		String fileType = "image" + File.separator + "jpg";
		response.setContentType(fileType);
		// 设置请求头 attachment;打开文件不需要配置,下载需要 
		response.setHeader("Content-Disposition", "filename=" + fileName);
		String realPath = getRealPath(virtualPath + File.separator + fileName);
		try {
			copyFile(new BufferedInputStream(new FileInputStream(new File(realPath))),
					new BufferedOutputStream(response.getOutputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 复制文件方法
	 * 
	 * @param bin
	 * @param bos
	 * @throws IOException
	 */
	private void copyFile(BufferedInputStream bin, BufferedOutputStream bos) throws IOException {
		byte bytes[] = new byte[1024];
		int len = 0;
		while ((len = bin.read(bytes)) != -1) {
			bos.write(bytes, 0, len);
		}
		bin.close();
		bos.close();
	}

	/**
	 * 获取真实路径 项目发布地址
	 * 
	 * @param req
	 *            request 传入
	 * @param path
	 *            虚拟路径 + 图片名
	 * @return
	 */
	public String getRealPath(String path) {
		return this.request.getServletContext().getRealPath(path);
	}

	// 封装
	public File getFile() {
		return file;
	}

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

	public String getFileContentType() {
		return fileContentType;
	}

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

	public String getFileFileName() {
		return fileFileName;
	}

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

}

将这两个类copy入工程,然后搭建好Struts框架,然后再把下面的前端代码copy进去

当然action跳转地址是需要改变的切记哦。

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!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>Hello Struts</title>

</head>
<body>
	
	<h1>上传文件</h1>
	<form action="${pageContext.request.contextPath}/sy3/fileAction_uploadFile.action"
		method="post" enctype="multipart/form-data">
		<input type="submit"> <input type="file"
			name="file" />
	</form>
</body>
</html>

以及返回页面Success.jsp

这里的图片src直接去访问后台的action,当然你可以直接写你上传的图片,先上传然后跳转到该页面访问,如果没有先上传再来访问是会报错的哦!

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!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>跳转成功页面</title>
</head>
<body>
	<h1>Congratulation ! You had success to come here !</h1>
	<h1>被打开的图片</h1>
	<img alt="The picture doesn't exist"
		src="${pageContext.request.contextPath}/sy3/fileAction_openFile.action">
</body>
</html>

以上即是Struts上传下载文件方法,如有问题欢迎联系我。

猜你喜欢

转载自blog.csdn.net/qq_43227967/article/details/84073957