Struts2————學習筆記6 文件的上傳與下載 以及AJAX

文件上傳:

1)<form> 標籤中需要添加 enctype="multipart/form-data"屬性

2)在Action中添加接收文件的成員,成員的setter命名規則如下(X爲上傳文件名):

setX(File file)

setXContentType(String contentType)

setXFileName(String fileName)

3)設置文件保存路徑的時候使用

String path = ServletActionContext.getServletContext().getRealPath("/")

取得項目部署的真實路徑

File image = new FIle(path);

if(!image){

image.mkdir();  //創建目錄

}

if(image!=null){

File saveFIle = new File(image,imagename);

FileUtils.copyFile(image,saveFile);

}


限制所有上傳文件總大小:

<constant name="struts.multipart.maxSize" value="  " / >

限制單個文件大小:

<interceptor-ref name="fileUpload" >

<param name="maxinumSize">51200</param>

<param name="allowedTypes">image/bmp,image/gif</param>

</interceptor-ref>

默認攔截器(defaultStacks)需要置於fileUpload之後

多個文件上傳可以通過數組進行實現。

jpg圖片類型包括:pjpeg、jpeg


upload.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'upload.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

</head>

<body>
	<form method="post" action="my" name="frm" enctype="multipart/form-data">
		<p>
			照片:<input type="file" name="image">
		</p>
		<p>
			<input type="submit" value="上傳" name="button1"> <br>
		</p>
	</form>

</body>
</html>

Action:(單文件上傳)

package com.hlx.upload;

import java.io.File;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {
	// <input type="file" name="image">
	private File image; // 上傳的文件
	private String imageContentType; // 文件類型
	private String imageFileName; // 文件名

	public File getImage() {
		return image;
	}

	public void setImage(File image) {
		this.image = image;
	}

	public String getImageContentType() {
		return imageContentType;
	}

	public void setImageContentType(String imageContentType) {
		this.imageContentType = imageContentType;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		// 上傳的服務器路徑
		String path = ServletActionContext.getServletContext().getRealPath(
				"/upload");

		// 文件
		File filePath = new File(path);
		// 判斷文件是否存在
		if (!filePath.exists()) {
			filePath.mkdir();
		}

		System.out.println(image);
		System.out.println(filePath);
		System.out.println(imageContentType);
		System.out.println(imageFileName);

		return SUCCESS;
	}
}

Action:(多文件上傳)

package com.hlx.upload;

import java.io.File;

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

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction2 extends ActionSupport {
	// <input type="file" name="image">
	private File image[]; // 上傳的文件
	private String imageContentType[]; // 文件類型
	private String imageFileName[]; // 文件名

	public File[] getImage() {
		return image;
	}

	public void setImage(File[] image) {
		this.image = image;
	}

	public String[] getImageContentType() {
		return imageContentType;
	}

	public void setImageContentType(String[] imageContentType) {
		this.imageContentType = imageContentType;
	}

	public String[] getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String[] imageFileName) {
		this.imageFileName = imageFileName;
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		// 上傳的服務器路徑
		String path = ServletActionContext.getServletContext().getRealPath(
				"/upload");

		// 文件
		File filePath = new File(path);
		// 判斷文件是否存在
		if (!filePath.exists()) {
			filePath.mkdir();
		}

		if (image != null) {
			// 循環
			for (int i = 0; i < image.length; i++) {
				File saveFile = new File(filePath, imageFileName[i]);
				// 文件的複製
				FileUtils.copyFile(image[i], saveFile);
			}
		}

		return SUCCESS;
	}
}



struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>


	<!-- 限制所有文件上傳的大小 1KB=1024 50KB=50*1024 1M=1024*1024 -->
	<constant name="struts.multipart.maxSize" value="51200000"/>


	<package name="haha" namespace="/" extends="struts-default">


		<action name="my" class="com.hlx.upload.UploadAction">
			<interceptor-ref name="fileUpload">
				<!-- 文件過濾 -->
				<param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/pjpeg</param>
				<!-- 可以限制單個的文件上傳大小 -->
				<param name="maximumSize">512000</param>
			</interceptor-ref>
			<!--  默認攔截器必須放在fileUpload之後,否則無效 -->
			<interceptor-ref name="defaultStack" />
			<result>/index.jsp</result>
			<result name="input">/upload.jsp</result>
		</action>
		
		
		<action name="my2" class="com.hlx.upload.UploadAction2">
			<interceptor-ref name="fileUpload">
				<!-- 文件過濾 -->
				<param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/pjpeg</param>
				<!-- 可以限制單個的文件上傳大小 -->
				<param name="maximumSize">512000</param>
			</interceptor-ref>
			<!--  默認攔截器必須放在fileUpload之後,否則無效 -->
			<interceptor-ref name="defaultStack" />
			<result>/index.jsp</result>
			<result name="input">/upload2.jsp</result>
		</action>




	</package>
</struts>    


文件下載:

關鍵在於struts.xml配置:

<result name="success" type="stream">

<param name="contentType">text/plain</param>

<param name="contentDisposition">attachment:fileName="${fileName}"</param>

<param name="inputName">inputStream</param>  //文件流

<param name="bufferSize">1024</param>

</result>


BufferedInputStream  緩存輸入流


index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
      <h2>文件下載(必須服務器有這個文件@!!!):</h2><br/>  
      <a href="down.action?fileName=5.jpg">5.jpg點擊下載</a><br/>  
      <a href="down.action?fileName=1.jpg">1.jpg點擊下載</a><br/>  
  </body>
</html>


Action:

package com.hlx.down;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownAction extends ActionSupport {

	private String fileName; // 文件名

	private InputStream inputStream; // 文件流

	// 返回一個輸入流,作爲一個客戶端來說是一個輸入流,但對於服務器端是一個 輸出流
	public InputStream getInputStream() throws IOException {
		// 服務器路徑
		String path = ServletActionContext.getServletContext().getRealPath(
				"/upload");

		//返回文件流
		return new BufferedInputStream(new FileInputStream(path + "/"
				+ fileName));
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getFileName() {
		return fileName;
	}

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

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



struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<package name="hang" namespace="/" extends="struts-default">
		<action name="down" class="com.hlx.down.DownAction">
			<!-- 成功是文件流 -->
			<result name="success" type="stream">
				<param name="contentType">text/plain</param>  <!-- 文件類型 -->
				<param name="contentDisposition">attachment;fileName="${fileName}"</param>  <!-- 內容信息 -->
				<param name="inputName">inputStream</param>   <!-- 文件流 -->
				<param name="bufferSize">1024</param>  <!-- 緩存1024byte -->
			</result>
		</action>
	</package>
</struts>    


AJAX:

json-lib

struts-json-plugin

<package name="  " namespace="/" extends="json-default">

<action name="  " >

<result type="json">/....</result>

</action>

</package>


頁面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'login.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

<script type="text/javascript" src="js/jquery-1.8.3.js"></script>

<script type="text/javascript" src="js/login.js"></script></head>

<body>
	<div id="msg"></div>
	<form method="post" action="login" name="frm">
		<table border="1" width="346" height="123" align="center">
			<tbody>
				<tr>
					<td> name:</td>
					<td> <input type="text" name="user.uname">
					</td>
				</tr>
				<tr>
					<td> pass:</td>
					<td> <input type="password" name="user.upass">
					</td>
				</tr>
				<tr>
					<td> </td>
					<td>  <input type="button" value="登錄" id="button1">
						<input type="reset" value="重置" name="button2">
					</td>
				</tr>
			</tbody>
		</table>
	</form>

</body>
</html>

login.js:

//jQuery.getJSON(url, [data], [callback])
$(function() {

	// 點擊按鈕提交
	$("#button1").click(function() {
		// 獲得數據
		var name = $("[name=user.uname]").val();
		var pwd = $("[name=user.upass]").val();

		alert(name + "\t" + pwd);

		// 異步交換
		$.getJSON("login.action", {
			"user.uname" : name,
			"user.upass" : pwd
		}, function(data) {

			alert(data);

		});

	});

});




Action:

package com.hlx.ajax;

import com.hlx.entity.User;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

	private User user; // 封裝對象
	private String result; // 存放結果

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getResult() {
		return result;
	}

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

	@Override
	public String execute() throws Exception {
		if ("sa".equals(user.getUname()) && "aaa".equals(user.getUpass())) {
			result = "1";
		} else {
			result = "0";
		}
		return SUCCESS;
	}
}


Struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>

	<package name="hang" namespace="/" extends="struts-default">

		<action name="down" class="com.hlx.down.DownAction">
			<!-- 成功是文件流 -->
			<result name="success" type="stream">
				<param name="contentType">text/plain</param>  <!-- 文件類型 -->
				<param name="contentDisposition">attachment;fileName="${fileName}"</param>  <!-- 內容信息 -->
				<param name="inputName">inputStream</param>   <!-- 文件流 -->
				<param name="bufferSize">1024</param>  <!-- 緩存1024byte -->
			</result>

		</action>
	</package>
</struts>    




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章