struts2 中文件的上传与下载
在很多时候,我们需要对文件进行上传与下载的处理。也许你知道jspsmartupload哪个拥有上传与下载功能的那个组件,这里小编要给大家一同分享的是strust2版本中的文件的上传与下载。不足之处希望大家指正......
一、文件的上传步骤
1.修改提交的form表单中的enctype的属性,将其设置为复合的数据类型。即:enctype="multipart/form-data"
2.在action中定义三个属性。第一个属性来自jsp界面<input type="File" name="filePath"/>中德filePath,其余两个属性对应为filePathFileName,filePathContentType。用于获取文件名与文件的类型的。
3.在action自定义一个方法:用文件的读写操作对文件进行上传。
例子如下:
jsp页面如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s" %> <% 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> <s:fielderror /> <form action="upload.action" method="post" enctype="multipart/form-data"> <input name="title"><br /> <input type="file" name="uploadfile"><br /> <input type="submit" value="上传!" /> </form> </body> </html>
对应action中代码如下:
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class UploadAction extends ActionSupport{ private String title; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } private File uploadfile;//上传的内容 private String uploadfileFileName;//上传的文件名 private String uploadfileContentType;//上传的文件类型 public File getUploadfile() { return uploadfile; } public void setUploadfile(File uploadfile) { this.uploadfile = uploadfile; } public String getUploadfileFileName() { return uploadfileFileName; } public void setUploadfileFileName(String uploadfileFileName) { this.uploadfileFileName = uploadfileFileName; } public String getUploadfileContentType() { return uploadfileContentType; } public void setUploadfileContentType(String uploadfileContentType) { this.uploadfileContentType = uploadfileContentType; } public void upload(){ if(uploadfile!=null){ String url = ServletActionContext.getServletContext().getRealPath("/")+"files/"; save(uploadfile,url+uploadfileFileName); System.out.println("文件上传成功了!!!!"+getUploadfileContentType()); } else{ System.out.println("上传的文件,不允许!!!"); } } public void save(File uploadfile,String url){ //将file写入磁盘文件 try { //创建读取流 FileInputStream fin = new FileInputStream(uploadfile); //创建写入流 File f = new File(url); FileOutputStream fout = new FileOutputStream(f); //一边读取,一边写入 byte data[] = new byte[1024]; int count = 0; //read()方法;将文件的数据读取到data数组中;返回读取到得个数. //1025 //1024--->data count = 1024 //1 --->data count = 1 //0 ---->data count = -1 while((count=fin.read(data))!=-1){ fout.write(data,0,count);//写入谁。data 0 读取的个数。 } //关闭流 fout.close(); fin.close(); } catch (Exception e) { e.printStackTrace(); } } }
至于配置就不用写了,哪个没有什么特殊的要求。如果你想控制上传的类型以及文件的大小,需要配置文件中配置相关参数,充其量就是一个拦截过滤的。。。可以在相关配置中找到o 0.0
二、strust2种文件的下载的步骤:
1.需要定义一个action,当然要记得将此类继承自actionsupport这个父类,并在其中定义一个属性,用于表示文件要下载的一个路径。
2.需要在action中定义一个返回值为InputStream的方法,并且方法名称需要如getTargetFile这种命名规则,即:get+一个名称,一个名称的首写字母必须是大写的.
例子如下:
jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s" %> <% 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> <hr /> 下载文件:<br /> <a href="download.action?downloadFile=我是中文哟.html">下载html</a><a href="download.action?downloadFile=xwork-core-2.2.1-sources.jar">下载jar</a> </body> </html>
对应的action的代码:
import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URLEncoder; import org.apache.struts2.ServletActionContext; /** * * 下载的Action * * @author Administrator * */ public class DownloadAction { //定义属性,表示需要下载的文件名 private String downloadFile; public String getDownloadFile() { return downloadFile; } public void setDownloadFile(String downloadFile) { try { this.downloadFile = new String(downloadFile.getBytes("ISO-8859-1"),"UTF-8"); System.out.println(this.downloadFile); } catch (Exception e) { e.printStackTrace(); } //this.downloadFile = downloadFile; } //需要完成下载,必须定义方法;用于返回文件流;方法名命名规则:getXxx(); public InputStream getFileInfo(){ //设置响应的报头信息(中文问题的终极解决办法) try { ServletActionContext.getResponse() .setHeader("content-disposition", "attachment;fileName="+URLEncoder.encode(downloadFile,"UTF-8").toString()); String url = ServletActionContext.getServletContext().getRealPath("/")+"files/"+downloadFile; File f = new File(url); FileInputStream fin = new FileInputStream(f); return fin; } catch (Exception e) { e.printStackTrace(); } return null; } public String test(){ return "load"; } }
strust2.xml中配置文件的写法:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts (View Source for full doctype...)> - <struts> <constant name="struts.custom.i18n.resources" value="msg" /> <constant name="struts.multipart.maxSize" value="500" /> - <package name="mypk" extends="struts-default" namespace="/"> - <result-types> <result-type name="hehe" class="com.sunspoter.lib.web.struts2.dispatcher.StreamResultX" default="false" /> </result-types> - <interceptors> - <interceptor name="myfileUpload" class="org.apache.struts2.interceptor.FileUploadInterceptor"> <param name="maximumSize">500</param> <param name="allowedTypes">image/pjpeg</param> </interceptor> </interceptors> - <action name="upload" class="com.zuxia.action.UploadAction" method="upload"> <interceptor-ref name="myfileUpload" /> <interceptor-ref name="defaultStack" /> <result name="input">/index.jsp</result> </action> - <action name="download" class="com.zuxia.action.DownloadAction" method="test"> - <result name="load" type="stream"> <param name="inputName">fileInfo</param> </result> </action> </package> </struts>