第八章:struts2文件上传下载
- 格式:ppt
- 大小:536.50 KB
- 文档页数:38
Struts2 结合HttpClient 实现远程服务器文件下载1、只实现远程文件下载未处理远程服务器连接失败的状态1.1、页面配置部分<button id="download" class="button" onclick="window.location.href = 'downlo adExample.action';return false;">下载模板</button><s:submit id="importButton" value="上传文件" theme="simple" cssClass="butto n"></s:submit><s:reset value="重置路径" theme="simple" cssClass="button" ></s:reset> 1.2、Struts2配置文件部分<!--下载模板--><action name="downloadExample" class="com.web.action.file.ImportAction "><param name="downFileName">文件下载.xls</param><result name="success" type="stream"><param name="contentType">application/vnd.ms-excel</param><param name="contentDisposition">attachment;filename="${downl oadName}"</param><param name="inputName">downloadFile</param><param name="bufferSize">4096</param></result></action>1.3、Action层中获取远程服务器文件流程序部分public class ImportAction{private String downFileName;private String downloadName;IFileServicefileService;/*** @paramfileService the fileService to set*/public void setEztFileService(IFileServicefileService) {this.fileService = fileService;}/*** @return the downFileName*/public String getDownFileName() {return downFileName;}/*** @paramdownFileName the downFileName to set*/public void setDownFileName(String downFileName) {this.downFileName = downFileName;}/*** @return the downloadName*/public String getDownloadName() {return downloadName;}/*** @paramdownloadName the downloadName to set*/public void setDownloadName(String downloadName) {this.downloadName = downloadName;}public InputStreamgetDownloadFile(){downloadName = fileService.getDownloadFileName(downFileName); //下载文件显示名称转编码Properties properties = ResourceUtil.getProperties("file.properties");//取得远程服务器信息配置属性文件file.properties文件为自定义文件放置在web项目src/conf文件夹下String strRemoteFileUrl = properties.getProperty("serverPath")+ propertie s.getProperty("templateName"); //取得远程文件路径InputStream in = fileService.getDownloadFile(strRemoteFileUrl); //调用S ervice层方法取得远程服务器文件流return in;}}1.4、Service层接口实现public class FileService implements IFileService {public String getDownloadFileName(String downFileName) { //解决下载文件名称中文乱码问题try {downFileName = new String(downFileName.getBytes(), "ISO-8859-1 ");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return downFileName;}publicInputStreamgetDownloadFile(String strRemoteFileUrl) {// TODO Auto-generated method stubHttpClient client = new HttpClient();GetMethodhttpGet = new GetMethod(strRemoteFileUrl);InputStream in = null;try {intintResponseCode = client.executeMethod(httpGet);in = httpGet.getResponseBodyAsStream();} catch (HttpException e) {// TODO Auto-generated catch block//记录日志} catch (IOException e) {// TODO Auto-generated catch block//记录日志}return in;}}1.5、读取properties文件工具类部分public class ResourceUtil {public static Properties getProperties(String fileName) {try {Properties properties = new Properties();ClassLoader cl = Thread.currentThread().getContextClassLoader();properties.load(cl.getResourceAsStream(fileName));return properties;} catch (Exception ex) {ex.printStackTrace();}return null;}}1.6、总结:此项实现,在文件服务器运行正常的情况下文件下载正常,如果文件服务器运行异常或已停止运行则在jsp页面部分将会抛出异常。
struts上传和下载<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4"xmlns=""xmlns:xsi=""xsi:schemaLocation="/web-app_2_4.xsd"><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><filter><filter-name > struts2 </filter-name ><filter-class >org.apache.struts2.dispatcher.FilterDispatcher</filter-class ></filter ><filter-mapping><filter-name >struts2 </filter-name ><url-pattern > /* </url-pattern ></filter-mapping ></web-app>2》。
struts.xml文件:<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"""><struts><constant name="struts.il8n.encoding" value="GBK" /><constant name="struts.multipart.maxSize" value="102400000000" /><!-- 文件上传 --><constant name="struts.custom.i18n.resources" value="ApplicationResources" /><!-- 利用struts.multipart.saveDirg属性来改变临时文件存放的目录--><constant name="struts.multipart.saveDirg" value="e:\\temp" /><package name="default" extends="struts-default"><!-- 自定义下载时用拦截器 --><interceptors><interceptor name="download"class="org.sunxin.struts2.action.FileDownloadInterceptor" /> </interceptors><action name="upload" class="org.sunxin.struts2.action.FileUploadAction"><interceptor-ref name="defaultStack"><!-- 设置上传文件的大小及类型 --><!-- <param name="fileUpload.maximumSize">10240000</param>--> <param name="fileUpload.allowedTypes"> image/gif,image/jpg,image/bmp</param></interceptor-ref><result name="input">/upload.jsp</result><result name="success">/success.jsp</result><param name="uploadDir">/WEB-INF/UploadFiles</param> </action><!-- 文件下载 1--><action name="download" class="org.sunxin.struts2.action.FileDownloadAction"> <!-- 指定下载文件的路径,该路径相对于web应用程序所在的目录 --><param name="inputPath1">/WEB-INF/UploadFiles/65_Fetch_2.avi</param><param name="inputPath2">/WEB-INF/UploadFiles/AJAX.bmp</param><result name="success" type="stream"><!-- 指定下载文件内容类型 application/zip --><param name="contentType">imag/bmp,*./avi</param> <!--inputName默认值是InputStream,如果action中用于读取下载文件内容的属性名是inputStream,那麽可以省略这个参数--><param name="inputName">InputStream</param><paramname="contentDisposition">filename="${filename}"</param> <param name="bufferSize">2048</param></result></action></package></struts>3》。
Struts2上传下载续上传续在昨天的笔记中,我们学习了struts2的基本上传方法,并完成了一个上传的实例,下面我们在学习上传的一些相关知识。
1.在上传中,我们写的小程序是可以上传任何类型文件的,可是在我们的真实开发中,一定会对上传文件的类型进行严格的控制,那我们该如何对上传文件的类型进行控制呢,我们前面已经学习了struts2的核心部分——拦截器,拦截器的功能十分的强大,那么下面我们就用拦截器来实现对上传文件的类型控制。
Struts2已经对上传有了默认的拦截器,我们就用struts2的默认拦截器进行类型控制,首先我们来看下我们所需要的拦截器:①.打开struts-default.xml文件,找到<interceptors>标签,我们找到了我们需要的拦截器,名为fileUpload,该拦截器的定义如下:<interceptor name="fileUpload" class="org.apache.struts2.interceptor.FileUploadInterceptor"/>②.根据上面的定义,我们找到了org.apache.struts2.interceptor.FileUploadInterceptor类③.我们关联源码,打开FileUploadInterceptor类,我们找到了如下信息:④.下面我们就要在struts.xml文件中进行拦截器的配置⑤.我们将fileUpload拦截器配置到我们的action中,可是类型该怎么写呢,没关系,我们可以在tomcat的conf目录下的web.xml文件中查找,例如,我们只允许上传以ppt为扩展名的文件,按Ctrl+F查找,输入PPT,出现下面结果:⑥.我们将<mime-type>标签中的内容复制到struts.xml中我们配置的拦截器中的<param>标签下,如④中的图。
tomcat上传文件下载文件首先介绍一下我们需要的环境:我用的是myeclipse8.5的java开发环境,tomcat是用的apache-tomcat-6.0.26这个版本。
首先先需要准备一下使用到的jar包这些jar包是struts2的jar包。
这些jar包是都是用于上传文件的。
注意:这里的jar包版本必须是对应的,如不是可能会tomcat下报错。
所以大家最好注意一下啊。
最好是用这套jar包。
我将会在csdn上将项目jar包发上去。
Jar下载地址(0分):/detail/woaixinxin123/4193113 源代码下载(10分):/detail/woaixinxin123/4193134开始搭建我们的项目。
创建web项目名字为File。
第一步:搭建struts2框架。
1、到jar包。
2、编辑web.xml<?xml version="1.0"encoding="UTF-8"?><web-app version="2.5"xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_2_5.xsd"><!-- 增加struts2的支持 --><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepa reAndExecuteFilter</filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>3、添加struts.xml<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""/dtds/struts-2.0.dtd"><struts></struts>4、启动tomcat测试。
Struts2实现文件上传文件上传,说白了就是个文件复制的过程,文件复制需要什么呢,只需要有源文件和目标地址即可,·用main方法实现的文件复制代码如下:package cn.oracle.upload;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;public class FileUploadDemo {public static void main(String[] args) throws Exception{File input=new File(args[0]); 参数args[0]是你运行Java程序的时候输入的参数,下面有详细解释:if(!input.exists()){System.out.println("源文件不存在!");System.exit(0);}File output=new File(args[1]);if(!output.getParentFile().exists()){output.mkdirs();}OutputStream outputFile=new FileOutputStream(output);InputStream inputFile=new FileInputStream(input);byte data[]=new byte[1024];int temp=0;while((temp=inputFile.read(data))!=-1){outputFile.write(data, 0, temp);}outputFile.close();inputFile.close();}}例如上图中的Java 运行的程序类名称后面就是参数第一个是d:\1.txt 是一个参数args[0],d:\2.txt是第二个参数args[1]C:\Users\congz_000>java FileUploadDemo d:\1.txt d:\2.txt上面的代码就实现了文件的复制,其实在struts2之中的实现原理是一样的,也就是两个File对象,两个字节流对象,然后调用相应的方法执行的复制而已;在struts2之中实现的复制需要一个表单,将此表单的内容提交到一个action之中,然后struts负责参数的接受处理,赋给相应的变量,编写一个文件复制的方法即可完成文件上传;·给项目添加struts2开发支持,我们用自动配置的方式,用myeclipse帮我们完成,不需要做过多的配置,一路next即可;·新建一个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><title>文件上传</title></head><body><form action="FileUpload!upload.action"method="post"enctype="multipart/form-data"><input type="file"name="photo"id="photo"> 这个name属性一定要和action之中的File 类对象的名称一致;<input type="submit"value="上传"></form></body></html>·一个用来表示上传成功的页面<%@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><title>文件上传</title></head><body><h1>上传成功</h1></body></html>·一个用来表示上传失败的页面<%@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><title>文件上传</title></head><body><h2>上传失败!</h2></body></html>·编写相应的上传需要的action FileUploadActionpackage cn.oracle.action;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.UUID;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;@SuppressWarnings("serial")public class FileUploadAction extends ActionSupport { private File photo;private String photoFileName;public void setPhotoFileName(String photoFileName) { this.photoFileName = photoFileName;}public void setPhoto(File photo) {this.photo = photo;}public String upload(){System.out.println("************");String filePath =ServletActionContext.getServletContext().getRealPath("/upload")+ File.separator+ UUID.randomUUID()+ "."+ this.photoFileName.substring(this.photoFileName.lastIndexOf(".") + 1);if(this.saveFile(this.photo, filePath)){return"success";}return"failure";}public boolean saveFile(File input, String outputFilePath) { File output = new File(outputFilePath);if (!output.getParentFile().exists()) {output.mkdirs();}InputStream inputFile = null;try {inputFile = new FileInputStream(input);} catch (FileNotFoundException e) {e.printStackTrace();}OutputStream outputFile = null;try {outputFile = new FileOutputStream(output);} catch (FileNotFoundException e) {e.printStackTrace();}byte[] data = new byte[1024];int temp = 0;try {while ((temp = inputFile.read(data)) != -1) {outputFile.write(data, 0, temp);}if (inputFile != null) {inputFile.close();}if (outputFile != null) {outputFile.close();}return true;} catch (Exception e) {e.printStackTrace();}return false;}}·配置Struts.xml文件<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN""/dtds/struts-2.1.dtd"><struts><package name="main"namespace="/"extends="struts-default"><action name="FileUpload"class="cn.oracle.action.FileUploadAction"> <result name="success">/success.jsp</result><result name="failure">/failure.jsp</result></action></package></struts>·我们还需要配置一个Struts.properties的资源文件,在src之中,设置上传的限制和编码;struts.i18n.encoding=UTF-8struts.multipart.saveDir=/tempstruts.multipart.maxSize=2097152000·我们把项目部署到tomcat或者weblogic之中,按照你的连接访问,整个上传到此就完成了,这是个最简单的上传,没有做任何的修饰,有些上传做的很华丽的,那些都是div+css的功劳,如果你想要那种特效的话,需要研究下css 这个很不错的;。
【java入门与精通】Struts2上传下载---上海腾科上传import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class SingleFileUploadAction extends ActionSupport{private File myFile;//fileName:文件名称,由struts调用赋值private String myFileFileName;//contentType:文件类型,由struts调用赋值private String myFileContentType;//fileName、contentType都需要添加get、set方法//注意:注意上面3个定义的upload是相同的,也就是说你命名时,要一致public String execute() throws Exception{//保存路径对象StringconservePath=ServletActionContext.getServletContext().getRealPath("/uploa d");//注意:第二个参数必须是fileNameFile conserveFile=new File(conservePath, this.getMyFileFileName());copy(myFile,conserveFile);System.out.println("文件上传成功...");return "singleFileUpload";}public File getMyFile() {return myFile;}public void setMyFile(File myFile) {this.myFile = myFile;}public String getMyFileFileName() {return myFileFileName;}public void setMyFileFileName(String myFileFileName) { this.myFileFileName = myFileFileName;}public String getMyFileContentType() {return myFileContentType;}public void setMyFileContentType(String myFileContentType) { this.myFileContentType = myFileContentType;}//拷贝文件/** srcFile:客户端传服务器的文件对象(struts2帮我们完成)* destFile:将客户端传过来的文件写到的目标文件对象(需要我们完成) */public void copy(File srcFile,File destFile) {System.out.println("srcFile==>"+srcFile.getAbsolutePath());System.out.println("destFile==>"+destFile.getAbsolutePath());BufferedInputStream bis = null;BufferedOutputStream bos = null;try {FileInputStream fis = new FileInputStream(srcFile);FileOutputStream fos = new FileOutputStream(destFile);bis = new BufferedInputStream(fis);bos = new BufferedOutputStream(fos);byte[] buf = new byte[1012];int length = 0;while((length = bis.read(buf))!=-1){bos.write(buf,0,length);}bos.flush();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch(IOException ex){ex.printStackTrace();}finally{if(bis!=null){try {bis.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(bos!=null){try {bos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}上传页面:<s:form action="fileuploadAction.action" method="post"enctype="multipart/form-data"><s:file name="myFile"label="选择文件"></s:file><s:submitvalue="提交"align="center"></s:submit></s:form>配置struts.xml文件<interceptor-ref name="fileUpload"><!-- struts2 上传默认为二进制格式<param name="allowedTypes">application/zip,text/plain,application/vnd.ms-powerpoint,application/x-java script,text/html,application/octet-stream,application/msword,image/bmp,image /png,image/gif,image/jpeg,image/jpg</param>2097152--><!-- 设置上传文件大小2mb,如果上传的文件过大,则会抛出异常:ng.RuntimeException: Invalid action class configuration that references an unknown class nam --><param name="maximumSize">2097152</param></interceptor-ref><interceptor-ref name="fileUploadStack" /><interceptor-ref name="defaultStack" />注意:1、必须在form表单中添加enctype="multipart/form-data"2、form表单必须是post提交方式下载download.class://下载文件名private String downloadFileName;//用于获取要下载的文件名public String getDownloadFileName() {//查询获取文件名String fileName = sm.downloadSource(source.getSourceId());System.out.println("^^^^^^^^^^^^^^^^fileName="+fileName);return fileName;}//用于获取io流:输入流public InputStream getFileStream() throws Exception {//创建要下载文件的输入流InputStreamis=ServletActionContext.getServletContext().getResourceAsStream("/upload/" +this.getDownloadFileName());return is;}struts.xml:<!-- 下载--><result name="DownloadAjax" type="stream"><paramname="contentType">application/octet-stream</param><paramname="contentDisposition">attachment;filename="${downloadFileName}"</pa ram>//在action类中调用getDownloadFileName()方法,获取创建的文件名<param name="inputName">fileStream</param>//调用action 类中的getFileStream()方法,获取下载文件的输入流<param name="bufferSize">2097152</param></result>注意:如果buffersize设置的太小,或getFileStruem出问题,则会抛出:ng.IllegalArgumentException: Can not find a java.io.InputStream with the name [fileStream] in the invocation stack. Check the tag specified for this action.异常。
Struts2文件上传完美解决中文乱码问题步骤/方法笔者的Struts2版本号是2.2.3,如果你的是2.0版本以上也没关系。
创建的java project项目名字为:uploads,各个文件、页面编码统一为:UTF-8。
首先导入Struts所依赖或自身的jar包,我们直接导入struts官方给出的空白实例所用到的jar包,分为:asm-3.1.jar、asm-commons-3.1.jar、asm-tree-3.1.jar、commons-fileupload-1.2.2.jar、commons-io-2.0.1.jar、commons-lang-2.5.jar、freemarker-2.3.16.jar、javassist-3.11.0.GA.jar、ognl-3.0.1.jar、struts2-core-2.2.3.jar、xwork-core-2.2.3.jar,这些包位于\struts-2.2.3\apps\struts2-blank\WEB-INF\lib目录下,如果你和笔者所使用的struts版本不一致,请直接导入该目录下的所有文件。
uploads\WebRoot\WEB-INF\web.xml<?xml version="1.0"encoding="UTF-8"?><web-app version="2.5"xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_2_5.xsd"><filter><filter-name>uploads</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filte r-class></filter><filter-mapping><filter-name>uploads</filter-name><url-pattern>/*</url-pattern></filter-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>uploads\src\struts.xml(注意:如果你的版本和笔者的不一样可以展开struts2-core-2.2.3.jar,打开struts-default.xml文件,大概在24-26行DOCTYPE内容替换以下粗体)<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN""/dtds/struts-2.1.7.dtd"><struts><constant name="struts.i18n.encoding"value="UTF-8"></constant><package name="uploads"extends="struts-default"><action name="uploads"class="com.tarena.action.FileUploadAction"> <result name="success"type="redirect">/index.jsp</result> </action></package></struts>uploads\src\com\tarena\action\FileUploadAction.javapackage com.tarena.action;public class FileUploadAction extends ActionSupport {private File file; // 这个和以下的内容在struts中有特殊的要求,具体请翻阅相关资料。
一、Struts2实现文件上传1、添加必备jar包commons-logging-1.1.jarfreemarker-2.3.8.jarognl-2.6.11.jarstruts2-core-2.0.6.jarxwork-2.0.1.jarcommons-io-1.3.1.jarcommons-fileupload-1.2.jar2、jsp页面设置1)表单的提交方式必须为post2)表单标签必须添加属性enctype="multipart/form-data"3)表单元素file添加name属性3、Action类的编写1)根据表单元素file的name属性声明三个对应属性,一个是File类型,两个是字符串类型,并且三个属性名字固定,分别用于存储上传的文件,文件名及文件类型private file name属性名;private String name属性名FileName;private String name属性名ConentType;并提供对应的setter/getter方法2)在execute方法中编写代码Stringpath=ServletActionContext.getServletContext().getRealPath("/")+"/ images/"+headerFileName;FileUtils.copyFile(header, new File(path));3)如果一次上传多个文件,则需要保证所有上传控件的名字相同,在Action中声明三个集合或数组来接收上传上来的所有文件信息,并在execute方法中操作文件集合或数组即可for(int i=0;i<header.size();i++){File file=header.get(i);if(file!=null && file.exists()){Stringpath=ServletActionContext.getServletContext().getRealPath("/")+"/imag es/"+headerFileName.get(i);FileUtils.copyFile(file, new File(path));}}4、struts.xml配置文件1)注意,上传使用的action必须引用了fileupload拦截器,默认拦截器栈中已经包含了次拦截器了;只需注意如果引用了自定义拦截器,默认拦截器无效了;2)可以通过配置一些常量值,来控制上传文件的大小<constant name="struts.multipart.maxSize"value="1024000"></constant> 二、Struts2实现文件下载1、添加必备jar包commons-logging-1.1.jarfreemarker-2.3.8.jarognl-2.6.11.jarstruts2-core-2.0.6.jarxwork-2.0.1.jarcommons-io-1.3.1.jarcommons-fileupload-1.2.jar2、jsp页面设置<a href="download.action?fileName=${'权限练习.doc' }">权限需求文档</a><a href="download.action?fileName=${'Wind.jpg' }">风景画</a>提供超链接进行下载,点击时提交给action,并提供要下载的文件的名字及地址2、Action类的编写1)创建属性,接收提交过来的路径名及文件名,并提供getter/setter方法2)exectue方法直接return即可,无需编写任何代码3)编写下载方法public InputStream getDownloadFile()throws IOException{Stringpathname=ServletActionContext.getServletContext().getRealPath("/")+"/ images/"+fileName;HttpServletResponseresponse=ServletActionContext.getResponse();response.setContentType("application/x-msdownload");FileInputStream stream=new FileInputStream(new File(pathname));try {response.setHeader("Content-Disposition","attachment;filename="+newString(fileName.getBytes("gbk"),"iso-8859-1"));} catch (Exception e) {System.out.println("error:"+e.getMessage());}return stream;}注意此方法是自定义的,注意方法名字,必须符合驼峰命名法,以get开头即可3、struts.xml配置文件<action name="download"class="cn.mystruts.action.DownloadAction"> <result name="ok"type="stream"><param name="inputName">downloadFile</param><param name="bufferSize">1024</param></result></action>注意:1、参数inputName给的值是所编写的下载方法的名字去掉get,并要求符合驼峰命名法2、在tomcat/conf/server.xml中修改默认端口号的connector节点后添加属性URIEncoding=”UTF-8”。
1. struts2中的文件上传第一步:在WEB=INF/lib下加入commons-fileupload-1.2.1.jar ,commons-io-1.3.2.jar。
第二步:把form表单的enctype属性设置为"multipart/form-data",如Java代码1.<form action="${pageContext.request.contextPath}/control/employee/list_execute.action" enctype="multipart/form-data" method="p ost">2.文件:<input type="file" name="image">3. <input type="submit" value="上传"/>4. </form>5. //${pageContext.request.contextPath}:获取服务器根路径第三步:在action中添加一下属性,Java代码1.public class HelloWorldAction {2. private File image; //与jsp表单中的名称对应3. private String imageFileName; //FileName为固定格式4. private String imageContentType ;//ContentType为固定格式5.6. public String getImageContentType() {7. return imageContentType;8. }9. public void setImageContentType(String imageContentType) {10. this.imageContentType = imageContentType;11. }12. public String getImageFileName() {13. return imageFileName;14. }15. public void setImageFileName(String imageFileName) {16. this.imageFileName = imageFileName;17. }18. public File getImage() {19. return image;20. }21. public void setImage(File image) {22. this.image = image;23. }24. public String execute() throws Exception{25.System.out.println("imageFileName = "+imageFileName);26.System.out.println("imageContentType = "+imageContentType);27. //获取服务器的根路径realpath28. String realpath = ServletActionContext.getServletContext().getRealPath("/images");29.System.out.println(realpath);30. if(image!=null){31. File savefile = new File(new File(realpath), imageFileName);32. if(!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs();33. FileUtils.copyFile(image, savefile);34. ActionContext.getContext().put("message", "上传成功");35. }else{36. ActionContext.getContext().put("message", "上传失败");37. }38. return "success";39. }40.}此外,可以在struts.xml中配置上传文件的大小<constant name="struts.multipart.maxSize" value="10701096"/> //最大上传配置成10M默认的上传大小为2M思维拓展:如果要上传的文件非常大,如上传的是电影,好几百M ,用web上传一般是不可能难上传成功的,这时候要安装一个插件,类似于应用程序socket ,通过网络通讯上传。
Struts2实现的文件上传功能一,单个文件上传 (2)Jsp页面 (2)Action层代码 (2)Struts.xml配置文件中代码 (4)上传成功跳转页面代码 (5)二,多文件上传 (5)Jsp页面 (5)Action层代码 (6)Struts配置文件(与单个一样) (8)上传成功后显示页面 (8)文件上传,类型的拦截,具体请看action的配置 (9)一,单个文件上传Jsp页面<!-- 错误处理,如果不是指定的文件报错,指定的文件类型在struts.xml文件中--><s:fielderror/><s:form action="fileUpload"method="post" enctype="multipart/form-data"><!—这个myFile与后面action里面私有变量对应--><s:file name="myFile"label="image File"/><s:submit/><s:reset/></s:form>Action层代码public class FileFloadAction extends ActionSupport{private static final int BUFFER_SIZE = 16 * 1024;// 与jsp页面<s:file name="myFile"/>的name对应private File myFile;// 通过myFile自动传递过来ContentType,起名为file的名字+ContentTypeprivate String myFileContentType;// 文件的名字,与上ContentType类似,起名为file的名字+FileName private String myFileFileName;// 图片的名字private String imageFileName;****************************************************此处生成get,set方法****************************************************//得到文件的名字与类型,并返回private static String getExtention(String myFileFileName) {int pos = stIndexOf("\\");return myFileFileName.substring(pos + 1);//实现文件的拷贝private static void copy(File src, File dst){try{InputStream in = null;OutputStream out = null;try{in = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);byte[] buffer = new byte[BUFFER_SIZE];//修正后的copyfor (int byteRead = 0; (byteRead =in.read(buffer)) > 0;){out.write(buffer, 0, byteRead);}}finally{if (null != in)in.close();if (null != out)out.close();}}catch (Exception e){e.printStackTrace();}}public String fileFload()//名字可以取时间+类型(不会重复)// imageFileName = new Date().getTime() + getExtention(fileName);//得到image的名字及类型imageFileName = getExtention(myFileFileName);//得到将要上传的目的地的路径String totalPath =ServletActionContext.getServletContext().getRealPath("/img");//在目的地创建一个文件File imageFile = new File(totalPath + "/" + imageFileName);//把要上传的文件复制到目的地文件中去copy(myFile, imageFile);return SUCCESS;}}Struts.xml配置文件中代码//文件上传<action name="fileUpload"class="com.forum.action.FileFloadAction"method="fileFload"> <interceptor-ref name ="fileUpload"><param name ="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param></interceptor-ref><interceptor-ref name ="defaultStack"/><result name="input">/fileUpload.jsp</result><resultname="success">/fileUploadSuccess.jsp</result></action>上传成功跳转页面代码<img alt="myfile" src="img/<s:propertyvalue="imageFileName"/>">二,多文件上传Jsp页面<!-- 错误处理,如果不是指定的文件报错,指定的文件类型在struts.xml文件中 --><s:fielderror/><s:form action="multipleFilesUpload"method="POST"enctype="multipart/form-data"><s:file label="File(1)"name="upload"/><s:file label="File(2)"name="upload"/><s:file label="FIle(3)"name="upload"/><s:submit/></s:form>Action层代码public class MultipleFilesUploadAction extends ActionSupport {private static final int BUFFER_SIZE = 16*1024;private List<File> uploads = new ArrayList<File>();private List<String> uploadFileNames = newArrayList<String>();private List<String> uploadContentTypes = newArrayList<String>();private List<String> imagesName = new ArrayList<String>(); ****************************************************此处生成get,set方法**************************************************** private static List<String> getExtention(List<String> filesName){List<String> lastNames = new ArrayList<String>();for(Iterator<String> iter =filesName.iterator();iter.hasNext(); ){int pos = stIndexOf("\\");lastNames.add(iter.next().substring(pos + 1));}return lastNames;}private static void copy(List<File> src, List<File> dst) {try{InputStream in = null;OutputStream out = null;try{for (int i = 0;i<src.size();i++){in = new BufferedInputStream(new FileInputStream(src.get(i)),BUFFER_SIZE);out = new BufferedOutputStream(new FileOutputStream(dst.get(i)),BUFFER_SIZE);byte[] buffer = new byte[BUFFER_SIZE];// 修正后的copyfor (int byteRead = 0; (byteRead =in.read(buffer)) > 0;){out.write(buffer, 0, byteRead);}}}finally{if (null != in)in.close();if (null != out)out.close();}}catch (Exception e){e.printStackTrace();}}public String multipleFilesUpload(){//得到文件的名字imagesName=getExtention(uploadFileNames);//将要存放文件路径折文件夹String totalPath = ServletActionContext.getServletContext() .getRealPath("/img");//生成文件List<File> imagesFile = new ArrayList<File>();for(Iterator<String> iter =imagesName.iterator();iter.hasNext();){imagesFile.add(new File(totalPath + "/" +iter.next()));}copy(uploads, imagesFile);return SUCCESS;}}Struts配置文件(与单个一样)<action name="multipleFilesUpload"class="com.forum.action.MultipleFilesUploadAction"method="multipleFilesUpload"><interceptor-ref name ="fileUpload"><param name ="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param></interceptor-ref><interceptor-ref name ="defaultStack"/><result name="input">/fileUpload.jsp</result><result name="success">/fileUploadSuccess.jsp</result> </action>上传成功后显示页面<s:iterator value="imagesName"><img alt="<s:property/>"src="img/<s:property/>"width="320px"height="240px"> </s:iterator>提示:上传的文件夹一定要在上传之前创建完成,本例是用的img文件夹,在webContext下面。
文件的上传和下载在J2EE编程已经是一个非常古老的话题了,也许您马上就能掰着指头数出好几个著名的大件:如SmartUpload、Apache的FileUpload。
但如果您的项目是构建在Struts+Spring+Hibernate(以下称SSH)框架上的,这些大件就显得笨重而沧桑了,SSH提供了一个简捷方便的文件上传下载的方案,我们只需要通过一些配置并辅以少量的代码就可以完好解决这个问题了。
文件的上传和下载在J2EE编程已经是一个非常古老的话题了,也许您马上就能掰着指头数出好几个著名的大件:如SmartUpload、Apache的FileUpload。
但如果您的项目是构建在Struts+Spring+Hibernate(以下称SSH)框架上的,这些大件就显得笨重而沧桑了,SSH提供了一个简捷方便的文件上传下载的方案,我们只需要通过一些配置并辅以少量的代码就可以完好解决这个问题了。
本文将围绕SSH文件上传下载的主题,向您详细讲述如何开发基于SSH的Web程序。
SSH各框架的均为当前最新版本:·Struts 1.2·Spring 1.2.5·Hibernate 3.0本文选用的数据库为Oracle 9i,当然你可以在不改动代码的情况下,通过配置文件的调整将其移植到任何具有Blob字段类型的数据库上,如MySQL,SQLServer等。
总体实现上传文件保存到T_FILE表中,T_FILE表结构如下:图1 T_FILE表结构其中:·FILE_ID:文件ID,32个字符,用Hibernate的uuid.hex算法生成。
·FILE_NAME:文件名。
·FILE_CONTENT:文件内容,对应Oracle的Blob类型。
·REMARK:文件备注。
文件数据存储在Blob类型的FILE_CONTENT表字段上,在Spring中采用OracleLobHandler来处理Lob字段(包括Clob和Blob),由于在程序中不需要引用到oracle 数据驱动程序的具体类且屏蔽了不同数据库处理Lob字段方法上的差别,从而撤除程序在多数据库移植上的樊篱。
一.在JSP环境中利用Commons-fileupload组件实现文件上传1.页面upload.jsp清单如下:Java代码1.<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>2.3.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML4.01 Transitional//EN">4.<html>5. <head>6. <title>The FileUpload Demo</title>7. </head>8.9. <body>10. <form action="UploadFile" method="post" enctype="multipart/form-data">11. <p><input type="text" name="fileinfo" value="">文件介绍</p>12. <p><input type="file" name="myfile" value="阅读文件"></p>13. <p><input type="submit" value="上传"></p>14. </form>15. </body>16.</html>注意:在上传表单中,既有一般文本域也有文件上传域2.FileUplaodServlet.java清单如下:Java代码1.package org.chris.fileupload;2.3.import java.io.File;4.import java.io.IOException;5.import java.util.Iterator;6.import java.util.List;7.8.import javax.servlet.ServletException;9.import javax.servlet.http.*;10.11.import org.apachemons.fileupload.FileItem;12.import org.apachemons.fileupload.FileItemFactory;13.import org.apachemons.fileupload.disk.DiskFileItemFactory;14.import org.apachemons.fileupload.servlet.ServletFileUpload;15.16.public class FileUplaodServlet extends HttpServlet {17.18. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {19. doPost(request, response);20. }21.22. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {23.24. request.setCharacterEncoding("UTF-8");25.26. //文件的上传部份27. boolean isMultipart = ServletFileUpload.isMultipartContent(request);28.29. if(isMultipart)30. {31. try {32. FileItemFactory factory = new DiskFileItemFactory();33. ServletFileUpload fileload = new ServletFileUpload(factory);34.35.// 设置最大文件尺寸,那个地址是4MB36. fileload.setSizeMax(4194304);37. List<FileItem> files = fileload.parseRequest(request);38. Iterator<FileItem> iterator = files.iterator();39. while(iterator.hasNext())40. {41. FileItem item = iterator.next();42. if(item.isFormField())43. {44. String name = item.getFieldName();45. String value = item.getString();46. System.out.println("表单域名为: " + name + "值为: " + value);47. }else48. {49. //取得取得文件名,此文件名包括途径50. String filename = item.getName();51. if(filename != null)52. {53. File file = new File(filename);54. //若是此文件存在55. if(file.exists()){56. File filetoserver = new File("d:\\upload\\",file.getName());57. item.write(filetoserver);58. System.out.println("文件 " + filetoserver.getName() + " 上传成功!!");59. }60. }61. }62. }63. } catch (Exception e) {64. System.out.println(e.getStackTrace());65. }66. }67. }68.}3.web.xml清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8"?>2.<web-app version="2.4"3. xmlns="java.sun/xml/ns/j2ee"4. xmlns:xsi="/2001/XMLSchema-instance"5. xsi:schemaLocation="java.sun/xml/ns/j2ee6. java.sun/xml/ns/j2ee/web-app_2_4.xsd">7.8. <servlet>9. <servlet-name>UploadFileServlet</servlet-name>10. <servlet-class>11. org.chris.fileupload.FileUplaodServlet12. </servlet-class>13. </servlet>14.15. <servlet-mapping>16. <servlet-name>UploadFileServlet</servlet-name>17. <url-pattern>/UploadFile</url-pattern>18. </servlet-mapping>19.20. <welcome-file-list>21. <welcome-file>/Index.jsp</welcome-file>22. </welcome-file-list>23.24.</web-app>二.在strut1.2中实现1.上传页面file.jsp 清单如下:Java代码1.<%@ page language="java" pageEncoding="ISO-8859-1"%>2.<%@ taglib uri="/struts/tags-bean" prefix="bean"%>3.<%@ taglib uri="/struts/tags-html" prefix="html"%>4.5.<html>6. <head>7. <title>JSP for FileForm form</title>8. </head>9. <body>10. <html:form action="/file" enctype="multipart/form-data">11. <html:file property="file1"></html:file>12. <html:submit/><html:cancel/>13. </html:form>14. </body>15.</html>2.FileAtion.java的清单如下:Java代码1./*2. * Generated by MyEclipse Struts3. * Template path: templates/java/JavaClass.vtl4. */5.package action;6.7.import java.io.*;8.9.import javax.servlet.http.HttpServletRequest;10.import javax.servlet.http.HttpServletResponse;11.import org.apache.struts.action.Action;12.import org.apache.struts.action.ActionForm;13.import org.apache.struts.action.ActionForward;14.import org.apache.struts.action.ActionMapping;15.import org.apache.struts.upload.FormFile;16.17.import form.FileForm;18.19./**20. * @author Chris21. * Creation date: 6-27-202022. *23. * XDoclet definition:24. * @struts.action path="/file" name="fileForm" input="/file.jsp"25. */26.public class FileAction extends Action {27. /*28. * Generated Methods29. */30.31. /**32. * Method execute33. * @param mapping34. * @param form35. * @param request36. * @param response37. * @return ActionForward38. */39. public ActionForward execute(ActionMapping mapping, ActionForm form,40. HttpServletRequest request, HttpServletResponse response) {41. FileForm fileForm = (FileForm) form;42. FormFile file1=fileForm.getFile1();43. if(file1!=null){44. //上传途径45. String dir=request.getSession(true).getServletContext().getRealPath("/upload");46. OutputStream fos=null;47. try {48. fos=new FileOutputStream(dir+"/"+file1.getFileName());49. fos.write(file1.getFileData(),0,file1.getFileSize());50. fos.flush();51. } catch (Exception e) {52. // TODO Auto-generated catch block53. e.printStackTrace();54. }finally{55. try{56. fos.close();57. }catch(Exception e){}58. }59. }60. //页面跳转61. return mapping.findForward("success");62. }63.}3.FileForm.java的清单如下:Java代码1.package form;2.3.import javax.servlet.http.HttpServletRequest;4.import org.apache.struts.action.ActionErrors;5.import org.apache.struts.action.ActionForm;6.import org.apache.struts.action.ActionMapping;7.import org.apache.struts.upload.FormFile;8.9./**10. * @author Chris11. * Creation date: 6-27-202012. *13. * XDoclet definition:14. * @struts.form name="fileForm"15. */16.public class FileForm extends ActionForm {17. /*18. * Generated Methods19. */20. private FormFile file1;21. /**22. * Method validate23. * @param mapping24. * @param request25. * @return ActionErrors26. */27. public ActionErrors validate(ActionMapping mapping,28. HttpServletRequest request) {29. // TODO Auto-generated method stub30. return null;31. }32.33. /**34. * Method reset35. * @param mapping36. * @param request37. */38. public void reset(ActionMapping mapping, HttpServletRequest request) {39. // TODO Auto-generated method stub40. }41.42. public FormFile getFile1() {43. return file1;44. }45.46. public void setFile1(FormFile file1) {47. this.file1 = file1;48. }49.}4.struts-config.xml的清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8"?>2.<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "/d tds/struts-config_1_2.dtd">3.4.<struts-config>5. <data-sources />6. <form-beans >7. <form-bean name="fileForm" type="form.FileForm" />8.9. </form-beans>10.11. <global-exceptions />12. <global-forwards />13. <action-mappings >14. <action15. attribute="fileForm"16. input="/file.jsp"17. name="fileForm"18. path="/file"19. type="action.FileAction"20. validate="false">21. <forward name="success" path="/file.jsp"></forward>22. </action>23.24. </action-mappings>25.26. <message-resources parameter="ApplicationResources" />27.</struts-config>5.web.xml代码清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8"?>2.<web-app xmlns="java.sun/xml/ns/j2ee" xmlns:xsi="w/2001/XMLSchema-instance" version="2.4" xsi:schemaLocatio n="java.sun/xml/ns/j2ee java.sun/xml/ns/j2ee/web-app_2_4.xsd">3. <servlet>4. <servlet-name>action</servlet-name>5. <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>6. <init-param>7. <param-name>config</param-name>8. <param-value>/WEB-INF/struts-config.xml</param-value>9. </init-param>10. <init-param>11. <param-name>debug</param-name>12. <param-value>3</param-value>13. </init-param>14. <init-param>15. <param-name>detail</param-name>16. <param-value>3</param-value>17. </init-param>18. <load-on-startup>0</load-on-startup>19. </servlet>20. <servlet-mapping>21. <servlet-name>action</servlet-name>22. <url-pattern>*.do</url-pattern>23. </servlet-mapping>24.</web-app>三.在struts2中实现(以图片上传为例)1.FileUpload.jsp代码清单如下:Java代码1.<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>2.<%@ taglib prefix="s" uri="/struts-tags" %>3.<html>4. <head>5. <title>The FileUplaodDemo In Struts2</title>6. </head>7.8. <body>9. <s:form action="fileUpload.action" method="POST" enctype="multipart/form-data">10. <s:file name="myFile" label="MyFile" ></s:file>11. <s:textfield name="caption" label="Caption"></s:textfield>12. <s:submit label="提交"></s:submit>13. </s:form>14. </body>15.</html>2.ShowUpload.jsp的功能清单如下:Java代码1.<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>2.<%@ taglib prefix="s" uri="/struts-tags" %>3.<html>4. <head>5. <title>ShowUpload</title>6. </head>7.8. <body>9. <div style ="padding: 3px; border: solid 1px #cccccc; text-align: center" >10. <img src ='UploadImages/<s:property value ="imageFileName"/> '/>11. <br />12. <s:property value ="caption"/>13. </div >14. </body>15.</html>3.FileUploadAction.java的代码清单如下:Java代码1.package com.chris;2.3.import java.io.*;4.import java.util.Date;5.6.import org.apache.struts2.ServletActionContext;7.8.9.import com.opensymphony.xwork2.ActionSupport;10.11.public class FileUploadAction extends ActionSupport{12.13. private static final long serialVersionUID = 572146812454l;14. private static final int BUFFER_SIZE = 16 * 1024 ;15.16. //注意,文件上传时<s:file/>同时与myFile,myFileContentType,myFileFileName绑定17. //因此同时要提供myFileContentType,myFileFileName的set方式18.19. private File myFile; //上传文件20. private String contentType;//上传文件类型21. private String fileName; //上传文件名22. private String imageFileName;23. private String caption;//文件说明,与页面属性绑定24.25. public void setMyFileContentType(String contentType) {26. System.out.println("contentType : " + contentType);27. this .contentType = contentType;28. }29.30. public void setMyFileFileName(String fileName) {31. System.out.println("FileName : " + fileName);32. this .fileName = fileName;33. }34.35. public void setMyFile(File myFile) {36. this .myFile = myFile;37. }38.39. public String getImageFileName() {40. return imageFileName;41. }42.43. public String getCaption() {44. return caption;45. }46.47. public void setCaption(String caption) {48. this .caption = caption;49. }50.51. private static void copy(File src, File dst) {52. try {53. InputStream in = null ;54. OutputStream out = null ;55. try {56. in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);57. out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);58. byte [] buffer = new byte [BUFFER_SIZE];59. while (in.read(buffer) > 0 ) {60. out.write(buffer);61. }62. } finally {63. if ( null != in) {64. in.close();65. }66. if ( null != out) {67. out.close();68. }69. }70. } catch (Exception e) {71. e.printStackTrace();72. }73. }74.75. private static String getExtention(String fileName) {76. int pos = stIndexOf(".");77. return fileName.substring(pos);78. }79.80.@Override81. public String execute() {82. imageFileName = new Date().getTime() + getExtention(fileName);83. File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages" ) + "/" + imageFileN ame);84. copy(myFile, imageFile);85. return SUCCESS;86. }87.}注:现在仅为方便实现Action因此继承ActionSupport,并Overrider execute()方式在struts2中任何一个POJO都能够作为Action4.struts.xml清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8" ?>2.<!DOCTYPE struts PUBLIC3. "-//Apache Software Foundation//DTD Struts Configuration2.0//EN"4. "/dtds/struts-2.0.dtd">5.<struts>6. <package name="example" namespace="/" extends="struts-default">7. <action name="fileUpload" class="com.chris.FileUploadAction">8. <interceptor-ref name="fileUploadStack"/>9. <result>/ShowUpload.jsp</result>10. </action>11. </package>12.</struts>5.web.xml清单如下:Java代码1.<?xml version="1.0" encoding="UTF-8"?>2.<web-app version="2.4"3. xmlns="java.sun/xml/ns/j2ee"4. xmlns:xsi="/2001/XMLSchema-instance"5. xsi:schemaLocation="java.sun/xml/ns/j2ee6. java.sun/xml/ns/j2ee/web-app_2_4.xsd">7. <filter >8. <filter-name > struts-cleanup </filter-name >9. <filter-class >10. org.apache.struts2.dispatcher.ActionContextCleanUp11. </filter-class >12. </filter >13. <filter-mapping >14. <filter-name > struts-cleanup </filter-name >15. <url-pattern > /* </url-pattern >16. </filter-mapping >17.18. <filter>19. <filter-name>struts2</filter-name>20. <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>21. </filter>22. <filter-mapping>23. <filter-name>struts2</filter-name>24. <url-pattern>/*</url-pattern>25. </filter-mapping>26. <welcome-file-list>27. <welcome-file>Index.jsp</welcome-file>28. </welcome-file-list>29.30.</web-app>。