文件的上传与下载



<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
	<head>
		<title>upload</title>

	</head>
	<%----%>
	<%--	<body>--%>
	<%----%>
	<%--		<s:actionerror />--%>
	<%--		<s:fielderror />--%>
	<%--		<s:form action="upload.action" method="POST" enctype="multipart/form-data">--%>
	<%--			<tr>--%>
	<%--				<td colspan="2">--%>
	<%--					<h1>--%>
	<%--						文件上传示例--%>
	<%--					</h1>--%>
	<%--				</td>--%>
	<%--			</tr>--%>
	<%--			<s:file name="upload" label="上传文件"/>--%>
	<%--			<s:file name="upload" label="上传文件"/>--%>
	<%--			<s:submit value="上   传" />--%>
	<%--		</s:form>--%>
	<%--	</body>--%>

	<body>

		<script type="text/javascript">

<!--addMore函数可以提供上传多个文件上传-->

function addMore()
{

	var td = document.getElementById("more");
	
	var br = document.createElement("br");
	var input = document.createElement("input");
	var button = document.createElement("input");
	
	input.type = "file";
	input.name = "upload";
	
	button.type = "button";
	button.value = "   删除    ";
	
	button.onclick = function()
	{
		td.removeChild(br);
		td.removeChild(input);
		td.removeChild(button);
	}
	
	td.appendChild(br);
	td.appendChild(input);
	td.appendChild(button);
}

</script>

		<!--<h3><font color="red">上传文件类型后缀为doc,ppt,xls,pdf,txt,java,每个文件大小不能大于50M</font></h3>-->

		<table align="center" width="50%">
			<tr>
				<td>

					<!--		<s:actionerror cssStyle="color:red"/>-->
					<s:fielderror cssStyle="color:red" />

				</td>
			</tr>
		</table>
		
		<s:form action="upload.action" theme="simple" method="post"
			enctype="multipart/form-data">

			<table align="center" width="50%" border="1">
				<tr>
					<td>
						上传文件
					</td>
					<td id="more" >
						<s:file name="upload"></s:file>
						<input type="button" value="上传更多..." onclick="addMore()">
					</td>
				</tr>
				<tr>
					<td>
						<s:submit value=" 确认 "></s:submit>
					</td>
					<td>
						<s:reset value=" 重置 "></s:reset>
					</td>
				</tr>

			</table>

		</s:form>

	</body>


</html>

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
	<head>
		<title>上传成功</title>
		<link href="<s:url value="/css/main.css"/>" rel="stylesheet"
			type="text/css" />
	</head>

	<body>
		<table class="wwFormTable">
			<tr>

				<td colspan="2">
					<h1>
						上传成功
					</h1>
				</td>
			</tr>

			<tr>
				<td class="tdLabel">
					<label for="doUpload_upload" class="label">
						内容类型:
					</label>
				</td>
				<td>
					<s:property value="uploadContentType" />
				</td>
			</tr>

			<tr>
				<td class="tdLabel">
					<label for="doUpload_upload" class="label">
						文件路径:
					</label>
				</td>
				<td>
					<s:property value="uploadFileName" />
				</td>
			</tr>


			<tr>
				<td class="tdLabel">
					<label for="doUpload_upload" class="label">
						临时文件:
					</label>
				</td>
				<td>
					<s:property value="upload" />
				</td>
			</tr>
		</table>

			



	</body>
</html>

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
	<head>
		<title>download</title>
	</head>
	<body>
		<%--	<s:iterator value="uploadFileName" id="downloadFileName">--%>
		<%--				<a href="download.action?name=<s:property value='%{#downloadFileName}'/>"><s:property value="%{#%{#downloadFileName}}" /> </a>--%>
		<%--				<br>--%>
		<%--	</s:iterator>--%>
		<table align="center" width="50%" border="1">
			<tr>
				<td align="center">
					文件下载
				</td>
			</tr>
			<c:forEach var="uploadFiles" items="${uploadFiles}">
				<tr>
					<td>
						<a
							href="download.action?name=${uploadFiles.uploadRealName }&realname=${uploadFiles.uploadFileName }">${uploadFiles.uploadFileName
							}</a>
					</td>
				</tr>

			</c:forEach>


		</table>
	</body>
</html>

public class UploadFiles
{
	private String uploadFileName;//上传的文件名称
	private String uploadContentType;//类型
	private String uploadRealName;//保存的文件真实名称,UUID
	//如果使用数据库的话,建议这三个字段都进行保存
	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 getUploadRealName()
	{
		return uploadRealName;
	}
	public void setUploadRealName(String uploadRealName)
	{
		this.uploadRealName = uploadRealName;
	}
	
	
}


import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
package com.neusoft.utils;
import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;
/**
 * 动态读取配置文件类
 * 
 * @author MZ
 *
 * @Time 2009-11-24下午08:25:22
 */
public class UploadConfigurationRead {

	/**
	 * 属性文件全名,需要的时候请重新配置PFILE
	 */
	private static String PFILE = "upload.properties";

	/**
	 * 配置文件路径
	 */
	private URI uri = null;

	/**
	 * 属性文件所对应的属性对象变量
	 */
	private long m_lastModifiedTime = 0;

	/**
	 * 对应于属性文件的文件对象变量
	 */
	private File m_file = null;

	/**
	 * 属性文件所对应的属性对象变量
	 */
	private Properties m_props = null;

	/**
	 * 唯一实例
	 */
	private static UploadConfigurationRead m_instance = new UploadConfigurationRead();

	/**
	 * 私有构造函数
	 * 
	 * @throws URISyntaxException
	 */
	private UploadConfigurationRead() {
		try {
			m_lastModifiedTime = getFile().lastModified();
			if (m_lastModifiedTime == 0) {
				System.err.println(PFILE + "file does not exist!");
			}
			m_props = new Properties();
			m_props.load(new FileInputStream(getFile()));

		} catch (URISyntaxException e) {
			System.err.println(PFILE+"文件路径不正确");
			e.printStackTrace();
		} catch (Exception e) {
			System.err.println(PFILE+"文件读取异常");
			e.printStackTrace();
		}
	}

	/**
	 * 查找ClassPath路径获取文件
	 * 
	 * @return File对象
	 * @throws URISyntaxException
	 */

	private File getFile() throws URISyntaxException {
		URI fileUri = this.getClass().getClassLoader().getResource(PFILE).toURI();
		m_file = new File(fileUri);
		return m_file;
	}

	/**
	 * 静态工厂方法
	 * 
	 * @return 返回ConfigurationRead的单一实例
	 */
	public synchronized static UploadConfigurationRead getInstance() {
		return m_instance;
	}

	/**
	 * 读取一特定的属性项
	 */
	public String getConfigItem(String name, String defaultVal) {
		long newTime = m_file.lastModified();
		// 检查属性文件是否被修改
		if (newTime == 0) {
			// 属性文件不存在
			if (m_lastModifiedTime == 0) {
				System.err.println(PFILE + " file does not exist!");
			} else {
				System.err.println(PFILE + " file was deleted!!");
			}
			return defaultVal;
		} else if (newTime > m_lastModifiedTime) {
			m_props.clear();
			try {
				m_props.load(new FileInputStream(getFile()));
			} catch (Exception e) {
				System.err.println("文件重新读取异常");
				e.printStackTrace();
			}
		}
		m_lastModifiedTime = newTime;
		String val = m_props.getProperty(name);
		if (val == null) {
			return defaultVal;
		} else {
			return val;
		}
	}

	/**
	 * 读取一特定的属性项
	 * 
	 * @param name
	 *            属性项的项名
	 * @return 属性项的值(如此项存在), 空(如此项不存在)
	 */
	public String getConfigItem(String name) {
		return getConfigItem(name, "");
	}

}




import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import com.neusoft.utils.UploadConfigurationRead;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

public class DownloadAction extends ActionSupport
{
	private static final long serialVersionUID = 6329383258366253255L;
	private String fileName;
	private String fileRealName;
	public void setFileName()
	{
		// 得到请求下载的文件名
		String fname = ServletActionContext.getRequest().getParameter("name");
		String frealname = ServletActionContext.getRequest().getParameter("realname");
		try
		{
			/*
			 * 对fname参数进行UTF-8解码,注意:实际进行UTF-8解码时会使用本地编码,本机为GBK。
			 * 这里使用request.setCharacterEncoding解码无效.
			 * 只有解码了getDownloadFile()方法才能在下载目录下正确找到请求的文件
			 */
			fname = new String(fname.getBytes("ISO-8859-1"), "UTF-8");
			frealname= new String(frealname.getBytes("ISO-8859-1"), "UTF-8");
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		this.fileName = fname;
		this.fileRealName = frealname;
//		System.out.println(fileName);
//		System.out.println(fileRealName);
	}

	/*
	 * @getFileName 此方法对应的是struts.xml文件中的: <param
	 * name="contentDisposition">attachment;filename="${fileName}"</param>
	 * 这个属性设置的是下载工具下载文件时显示的文件名, 要想正确的显示中文文件名,我们需要对fileName再次编码
	 * 否则中文名文件将出现乱码,或无法下载的情况
	 */
	public String getFileName() throws UnsupportedEncodingException
	{

		fileRealName = new String(fileRealName.getBytes(), "ISO-8859-1");

		return fileRealName;
	}

	/*
	 * @getDownloadFile 此方法对应的是struts.xml文件中的: <param
	 * name="inputName">downloadFile</param> 返回下载文件的流,可以参看struts2的源码
	 */
	public InputStream getDownloadFile()
	{

		this.setFileName();
		return ServletActionContext.getServletContext().getResourceAsStream("/"+UploadConfigurationRead.getInstance().getConfigItem("uploadFilePath").trim()+"/" + fileName);
	}

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

struts.properties


#Whether Struts is in development mode or not
struts.devMode=true
#Whether the localization messages should automatically be reloaded
struts.i18n.reload=true
#Whether to reload the XML configuration or not
struts.configuration.xml.reload=true

upload.properties:
uploadFilePath=upload/file

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<constant name="struts.i18n.encoding" value="utf8" />
	<constant name="struts.multipart.maxSize" value="10097152"></constant>
	
	<package name="file" namespace="/" extends="struts-default">
		<action name="showUpload">
			<result>/upload.jsp</result>
		</action>
		<action name="upload" class="com.neusoft.file.UploadAction">
			<result name="input">/upload.jsp</result>
<!--			<result name="success">/upload_success.jsp</result>-->
			<result name="success">/download.jsp</result>
			<interceptor-ref name="fileUpload">
<!--大家可以设置成自己的配置,想文件类型和大小等限制			-->
<!--				<param name="maximumSize">2097152</param>单位是字节	2M	(2097152B)		-->
<!--				<param name="allowedTypes">image/bmp,image/x-png,image/png,image/gif,image/jpeg,image/jpg,image/pjpeg</param>-->
<!--				-->
<!--					容许文件类型为doc,ppt,xls,pdf,txt,java-->
<!--				-->
			</interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
		</action>

		<action name="download" class="com.neusoft.file.DownloadAction">
			<result name="success" type="stream">
				<param name="contentDisposition">attachment;filename="${fileName}"</param>
				<param name="inputName">downloadFile</param>
			</result>
		</action>
	</package>
</struts>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值