使用Struts2实现简单的文件上传和下载

本文详细介绍了如何使用Struts2框架实现文件的上传与下载功能。首先讲解了文件上传的步骤,包括上传成功后的处理。接着,阐述了文件下载的实现,涉及所需jar包的导入、Struts2环境的搭建。在编写upload jsp页面和下载文件Action的基础上,重点解析了Struts核心配置文件struts.xml中的关键配置,如stream类型result的设置,包括contentType、inputName、contentDisposition和bufferSize等参数的作用和用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件上传和下载

上传


上传成功


文件下载



导入相应的jar包


搭建struts2环境 


编写上传jsp页面fileUp.jsp

<%@ 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>Insert title here</title>
</head>
<body>
	<div>
		<form action="fileupload" method="post" enctype="multipart/form-data">
			选择上传文件<input type="file" name="file"><br/>
			<input type="submit" value="上传">
		</form>
	</div>
</body>
</html>


编写上传文件的Action
package file.action;

import java.io.File;

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

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private File file;
	private String fileFileName;
	private String fileContentType;
	
	public String execute() throws Exception
	{
		String realPath = ServletActionContext.getServletContext().getRealPath("/file");
System.out.println(realPath);
		if (file != null)
		{
			File saveFile = new File(realPath + "\\" +fileFileName);
			
			if (!saveFile.getParentFile().exists())
			{
				saveFile.getParentFile().mkdirs();
			}
			
			FileUtils.copyFile(file, saveFile);
			return "success";
		}
		
		return "fail";
	}
	
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public String getFileFileName() {
		return fileFileName;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	public String getFileContentType() {
		return fileContentType;
	}
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	
	
}



编写上传文件和下载文件的jsp页面fileDownLoad.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>Insert title here</title>
</head>
<body>
	文件上传成功!<br/>
	上传的文件是:<a href="${ pageContext.request.contextPath }/download.action?fileName=<s:property value="fileFileName"/>"><s:property value="fileFileName"/></a>
	         
	点击文件名下载文件
</body>
</html>



编写下载文件的Action

package file.action;

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

import org.apache.struts2.ServletActionContext;

public class DownLoadAction
{
	private String fileName ;
	
	

	public String getFileName() 
	{
		return fileName;
	}

	public void setFileName(String fileName) 
	{	
		try 
		{
			//处理乱码
			fileName = new String(fileName.getBytes("ISO8859-1"));
		} 
		catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.fileName = fileName;
	}

	public InputStream getInputStream() throws Exception
	{
		System.out.println("文件名1:" + fileName); 
		System.out.println(ServletActionContext.getServletContext().getResourceAsStream("/file/"+fileName));
		return ServletActionContext.getServletContext().getResourceAsStream("/file/"+fileName);
	}
	
	public String execute() throws Exception
	{
		return "success";
	}
}


Struts的核心配置文件struts.xml

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

<struts>

	<!-- 配置Struts2国际化资源文件的baseName -->
	<constant name="struts.custom.i18n.resources" value="globalMessages"/>
	<!-- 配置Struts2应用的编码集  -->
	<constant name="struts.i18n.encoding" value="UTF-8"/>
	
	<package name="default" namespace="/" extends="struts-default">
		<!-- 配置下载的拦截器引用 -->
		<default-action-ref name="download"/>
		
		<!-- 文件上传Action -->	
		<action name="fileupload" class="file.action.FileUploadAction">
			<result name="success">/fileDownLoad.jsp</result>
		</action>
		
		<!-- 文件下载Action -->
		<action name="download" class="file.action.DownLoadAction">
			  <result type="stream">
               <param name="contentType">application/octext-stream</param>
               <param name="inputName">inputStream</param>
               <param name="contentDisposition">attachment;filename="${fileName}"</param>
               <param name="bufferSize">4096</param>
           </result>
		</action>
	</package>
</struts>

(1)当result为stream类型时,struts2会自动根据配置参数下载文件

(2)contentType参数:指定下载文件的文件类型———-application/octet-stream 表示无限制。

(3)inputName参数:流对象名——在Action中需要该输入流入口。

3-1 如果在action中声明的getInputStream()方法,在配置文件struts.xml中配置为

          <param name="inputName">inputStream</param>

3-2 如果在action中声明的getTargetFile()方法,在配置文件struts.xml中配置为

          <param name="inputName">targetFile</param>

3-3 使用该配置,他就会自动去找Action中的getInputsStream(或getTargetFile)方法。

(4)contentDisposition参数:指定文件下载的处理方式

4-1 内联方式(inline)表示浏览器尝试直接显示文件

4-2 附件方式(attachment)会弹出文件保存对话框,是默认方式,其格式为 attachment;filename="${fileName}"

(5)bufferSize参数:下载文件的缓冲大小。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值