struts2-文件的上传与下载(基本使用)

文章的知识点会多一些,请您务必耐心阅读,希望对您的学习会有所帮助!

1、文件上传

Struts2对文件上传进行了很好的封装,其文件上传主要依赖的是org.apache.struts2.interceptor.FileUploadInterceptor这个拦截器。
为了能上传文件,必须将表单的method设置为POST,将enctype设置为multipart/form-data,
让浏览器采用二进制流的方式处理表单数据。

<s:form action="login-user" method="post" enctype="multipart/form-data">

接下来介绍文件上传的基本步骤:
(1)修改jsp页面

	<body>
		<s:form action="login-user" method="post" enctype="multipart/form-data">
		
			<td colspan="2"><font size="6" color="gray">
			
			<s:text name="loginInterface"/></font></td>
			
			<s:file name="file" label="照片"></s:file>       //<---------
			
			<s:textfield name="username" key="loginName" />
			
			<s:password name="userpass" key="loginPassword" />
			
			<s:submit name="submit" key="loginSubmit" />
    	</s:form>
	</body>

箭头部分为上传按钮,其他部分我使用了国际化,有兴趣的小伙伴欢迎查看我关于国际化的博客。
界面效果图:
在这里插入图片描述
在这里插入图片描述
(2)修改Action实现类的代码

package com;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class LoginAction extends ActionSupport{
	private String strReturn=INPUT;	
	
	private File file;
	//注意:文件名称和文件类型的名称前缀必须相同
	//文件名称
	private String fileFileName;
	//文件类型
	private String fileContentType;
	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;
	}

	
private String username;
private String userpass;
public String getUsername() {
	return username;
}
public void setUsername(String username) {
	this.username = username;
}
public String getUserpass() {
	return userpass; 
}
public void setUserpass(String userpass) {
	this.userpass = userpass;
}


public String user() throws Exception{
	//获取上传文件后的存储路径
	String path = ServletActionContext.getServletContext().getRealPath("/image");
	//声明文件输入流,为输入流指定文件路径
	@SuppressWarnings("resource")
	FileInputStream in = new FileInputStream(file);
	//获取输出流,获取文件的文件地址及名称
	FileOutputStream out = new FileOutputStream(path+File.separator+fileFileName);
	byte[] b = new byte[1024];//每次写入的大小128个字节
	int len = 0;
	while((len=in.read(b))>0){
		out.write(b,0,len);
	}
	out.close();
	
	ActionContext la=ActionContext.getContext();
     if(getUsername().equals("1")&&getUserpass().equals("2019")||
    		 getUsername().equals("2")&&getUserpass().equals("2019"))
     {
    	 la.getSession().put("userlll",username);
		strReturn="user";
     }
     return strReturn;
 }

关键部分为user()方法里的代码;
上面Action中新包含了3个属性:file、fileFileName、fileContentType;分别用于封装上传文件、上传文件的文件名、上传文件的文件类型。

序号说明
类型为File的xxx属性封装了该文件域对应的文件内容
类型为string的xxxFileName属性封装了该文件域对应的文件的文件名
类型为string的xxxContentType属性封装了该文件域对应的文件的文件类型

(3)修改struts.xml

		<!--上传-->
		<action name="login-user" class="com.LoginAction" method="user">
			<interceptor-ref name="fileUpload">
				<param name="allowedTypes">image/png,image/jpg,image/jpeg</param>
				<param name="maximumSize">204800</param>
			</interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
			<result name="user">/welcome.jsp</result>
			<result name="input">/login.jsp</result>
		</action>	

这里我用了fileUpload这个拦截器过滤了文件上传的类型和大小。

(4)在跳转界面显示上传的图片

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta charset="UTF-8"></meta>
    <title>欢迎</title>
  </head>
  <body>
  	<center>
  		<font color="gray" size="5">
    <font size="10">登录成功!</font>
    
    <font>文件名:<s:property value="fileFileName" /><br></font>
    
	<font>文件类型:<s:property value="fileContentType" /><br></font>

    </font>   
    
    <img src= "<s:property value="'image/'+fileFileName"/> "/>
    
    </center>
  </body>
</html>

在这里插入图片描述

2、文件下载

虽然通过普通的超链接可以实现简单的文件下载功能,但是有种种弊端,比如不安全、文件名不支持中文等。使用struts2框架提供的下载功能,可以安全、高效地提供下载功能。Struts2提供了stream结果类型,该结果类型就是专门用于支持文件下载功能的。指定stream结果类型时,需要指定一个inputName参数,该参数指定了一个输入流,这个输入流是被下载文件的入口。
下面是下载的基本步骤:
(1)编写下载的Action (DownloadAction.java)

package com;

import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class DownloadAction extends ActionSupport{

	@SuppressWarnings("unused")
	private String inputPath;

	public InputStream getTargetFile() {
		//获取下载文件的路径
		return ServletActionContext.getServletContext().
		getResourceAsStream("image/l1.png");
	}

	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}	
}

这里我在WebContext目录下的image文件夹添加了l1.png图片,以实现指定路径下载。
在这里插入图片描述
(2)配置struts.xml

		<!--下载-->
		<action name="download" class="com.DownloadAction">
			<result type="stream">
				<!--指定文件下载类型 application/octet-stream默认值可以下载所有类型 -->
				<param name="contentType">image/png</param>
				
				<!--由getInputStream()方法获得inputStream -->
				<param name="inputName">targetFile</param>
				
				<!-- contentDisposition是文件下载的处理方式,
				包括内联(inline)和附件(attachment), 默认是inline -->
				<!--使用附件时这样配置:attachment;filename="文件名" -->
				<!--其中attachment;filename=${fileName},
				设置浏览器以下载的方式打开文件,文件下载的时候保存的名字应为${fileName},
				如果直接写filename=${fileName},那么默认情况是代表inline,
				浏览器会尝试自动打开它 -->
				<param name="contentDisposition">
				attachment;filename="${inputPath}"</param>
				
				<!-- 指定下载文件的缓存大小1024*4 -->
				<param name="bufferSize">4096</param>
				
			</result>
		</action>

(3)在跳转页面实现功能

   <s:a href="download">下载文件</s:a><br>

(4)效果图
在这里插入图片描述
我将其保存在桌面
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值