1. 程式人生 > >Struts框架上傳下載檔案輔助類,簡單實現Struts上傳圖片以及下載

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上傳下載檔案方法,如有問題歡迎聯絡我。