1. 程式人生 > >國慶七篇-----struts2的檔案上傳下載(一)

國慶七篇-----struts2的檔案上傳下載(一)

       struts2提供了檔案的上傳下載功能,不過需要我們對其提供相關的檔案引數。

比如檔案上傳,必須提供三種屬性,並對其提供setter和getter方法,而且必須按照以下規範命名:

private File XXX;

private String XXXFileName;

private String XXXContentType;   

注意:必須是上面的格式,即XXX,XXX+FileName,XXX+ContentType。如果不是上面的形式,攔截器不會對其賦值。

下面是程式碼:(MyFileUpload.java)

package com.hncj.edu;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class MyFileUpload extends ActionSupport{
	private File upload;
	private String uploadFileName;
	private String uploadContentType; //三種屬性格式固定
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String executeUpload() {
		String realPath = ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload");
		File uploadDir = new File(realPath);
		if(!uploadDir.exists()) {
			uploadDir.mkdir();
		}
		try {
                     //複製檔案呼叫copyFile就行了
			FileUtils.copyFile(upload, new File(realPath+File.separator+uploadFileName));
               		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "success";
	}
}

上傳檢視:(upload.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<s:actionerror/>
	<s:form action="upload" method="post" enctype="multipart/form-data">
		<s:file name="upload" label="請選擇檔案"></s:file>
		<s:submit label="提交"/>
	</s:form>
</body>
</html>

上傳成功後跳轉到下載檢視,顯示所有可以下載的檔案:(result.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
        //頁面中發出list.action請求,在showFileItems.jsp頁面中顯示所有檔案項,並將showFileItems.jsp的內容顯示在result.jsp頁面中
	<s:action name="list" executeResult="true"/>
</body>
</html>

showFileItems.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table>
		<s:iterator var="item" value="fileNames">
			<tr>
				<td>${item}</td>
				<td>
                                        //這裡要用url標籤,不然傳遞中文檔名會報錯
					<s:url var="url" value="download">
						<s:param name="fileName">${item}</s:param>
					</s:url>
                                        //使用上面url標籤定義的值
					<s:a href="%{#url}">下載</s:a>
				</td>
			</tr>
		</s:iterator>
	</table>
	<s:debug></s:debug>
</body>
</html>

顯示檔案項的Action:(ListAllFiles.java)

package com.hncj.edu;

import java.io.File;

import org.apache.struts2.ServletActionContext;

public class ListAllFiles {
	private String[] fileNames;

	public String[] getFileNames() {
		return fileNames;
	}

	public void setFileNames(String[] fileNames) {
		this.fileNames = fileNames;
	}
	
	public String listFiles() {
		String realPath = ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload");
		File dir = new File(realPath);
                //獲取上傳目錄下所有檔案的檔名
		fileNames = dir.list();
		return "success";
	}
}

下載的action:(MyFileDownload.java)

檔案下載必須要提供對應檔案的輸入流,為其賦值,並提供get方法。

package com.hncj.edu;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

public class MyFileDownload {
	private InputStream input; //必須的
	private String fileName; //還可以提供ContentType,ContentLength等屬性
	public InputStream getInput() {
		return input;
	}
	public void setInput(InputStream input) {
		this.input = input;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public String execute() {
		this.input = ServletActionContext.getServletContext().getResourceAsStream("/WEB-INF/upload"+"/"+fileName);
		return "success";
	}
}

strust.xml配置檔案

<?xml version="1.0" encoding="UTF-8" ?>

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


<struts>
    <constant name="struts.devMode" value="true"/>
    <package name="pack1" extends="struts-default">
    	<action name="upload" class="com.hncj.edu.MyFileUpload" method="executeUpload">
    		<interceptor-ref name="defaultStack">
                        <!--限制檔案上傳的大小-->
    			<param name="fileUpload.maximumSize">102400</param>
                        <!--限制檔案的字尾名-->
    			<param name="fileUpload.allowedExtensions">.txt</param>
                        <!--還可以限制檔案的型別-->
                        <param name="fileUpload.allowedTypes>image/jpeg<param>
    		</interceptor-ref>
    		<result name="success">result.jsp</result>
    		<result name="input">upload.jsp</result>
    	</action>
    	<action name="list" class="com.hncj.edu.ListAllFiles" method="listFiles">
    		<result>showFileItems.jsp</result>
    	</action>
    	<action name="download" class="com.hncj.edu.MyFileDownload">
    		<result type="stream">
                        <!--inputName要和action中的輸入流名字相同-->
    			<param name="inputName">input</param>
                        <!--設定下載方式開啟-->
    			<param name="contentDisposition">attachment;filename=${fileName}</param>
                        <!--設定緩衝區大小-->
    			<param name="bufferSize">4096</param>
    		</result>
    	</action>
    </package>
</struts>

執行結果: