Struts2文件上传与下载

1.1.1新建一个Maven项目(demo02)

在此添加Web构面以及 struts2 构面

1.2.1配置Maven依赖(pom.xml 文件)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <parent>
  8. <groupId>org.nf</groupId>
  9. <artifactId>parent</artifactId>
  10. <version>1.0-SNAPSHOT</version>
  11. <relativePath>../pom.xml</relativePath>
  12. </parent>
  13. <artifactId>demo02</artifactId>
  14. <packaging>war</packaging>
  15. <version>1.0-SNAPSHOT</version>
  16. </project> 

1.2.2 项目中pom文件所继承的父文件(pom.xml)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <artifactId>parent</artifactId>
  8. <groupId>org.nf</groupId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>pom</packaging>
  11. <properties>
  12. <!-- 设置整个maven项目的编码格式 -->
  13. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  14. <!-- 设置控制台输出参数的编码格式, 解决乱码 -->
  15. <orgLine>-Dfile.encoding=UTF-8</orgLine>
  16. </properties>
  17.  
  18. <build>
  19. <plugins>
  20. <!-- 配置maven编译插件,指定maven编译版本 -->
  21. <plugin>
  22. <!-- 插件名称 -->
  23. <artifactId>maven-compiler-plugin</artifactId>
  24. <!-- 插件配置信息 -->
  25. <configuration>
  26. <target>1.8</target>
  27. <source>1.8</source>
  28. <encoding>UTF-8</encoding>
  29. </configuration>
  30. </plugin>
  31.  
  32. <plugin>
  33. <!-- 插件名称 -->
  34. <groupId>org.apache.maven.plugins</groupId>
  35. <artifactId>maven-war-plugin</artifactId>
  36. <version>2.2</version>
  37. <configuration>
  38. <warSourceDirectory>web</warSourceDirectory>
  39. <webXml>web\WEB-INF\web.xml</webXml>
  40. </configuration>
  41. </plugin>
  42. </plugins>
  43. </build>
  44.  
  45. <!-- 添加Struts依赖 -->
  46. <dependencies>
  47. <dependency>
  48. <groupId>javax.servlet</groupId>
  49. <artifactId>javax.servlet-api</artifactId>
  50. <version>3.1.0</version>
  51. </dependency>
  52.  
  53. <dependency>
  54. <groupId>org.apache.struts</groupId>
  55. <artifactId>struts2-core</artifactId>
  56. <version>2.5.8</version>
  57. </dependency>
  58.  
  59. <dependency>
  60. <groupId>org.apache.struts</groupId>
  61. <artifactId>struts2-json-plugin</artifactId>
  62. <version>2.5.8</version>
  63. </dependency>
  64. </dependencies>
  65. </project>

1.2.3所添加好的依赖jar包如下:

1.3.1编写上传文件页面(upload.jsp)

  1. <%@ taglib prefix="s" uri="/struts-tags" %>
  2. <%--
  3. Created by IntelliJ IDEA.
  4. User: YongLin
  5. Date: 2017/2/9
  6. Time: 下午2:44
  7. To change this template use File | Settings | File Templates.
  8. --%>
  9. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  10. <html>
  11. <head>
  12. <title>Upload</title>
  13. </head>
  14. <body>
  15.  
  16. <!--方式一: 使用struts错误信息提示的标签,会自动输出错误信息 -->
  17. <s:fielderror cssStyle="color: red"/>
  18.  
  19. <!--方式二: 使用el表达式来获取错误信息,uploadFile对应input的name,它是一个数组
  20. 当多文件上传时,应该循环遍历这个数组来显示提示信息的内容-->
  21. <%--<font color="red">${fieldErrors.uploadFile[0]}</font>--%>
  22. <form method="post" action="upload" enctype="multipart/form-data">
  23. File:<input type="file" name="uploadFile"/><br/>
  24. Readme:<input type="text" name="readme"/><br/>
  25. <input type="submit" value="submit"/>
  26. </form>
  27. </body>
  28. </html>

运行效果:

1.4.1struts.xml文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <!DOCTYPE struts PUBLIC
  4. "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
  5. "http://struts.apache.org/dtds/struts-2.5.dtd">
  6.  
  7. <struts>
  8. <!-- 设置编码格式,防止上传的文件名为中文时是乱码 -->
  9. <constant name="struts.i18n.encoding" value="UTF-8"/>
  10. <!-- 指定resource资源文件的名称-->
  11. <constant name="struts.custom.i18n.resources" value="message"/>
  12. <!-- 设置上传文件的总大小(单位:字节),默认是10M -->
  13. <constant name="struts.multipart.maxSize" value="104857600"/>
  14.  
  15. <package name="struts" extends="struts-default,json-default">
  16. <!-- 配置上传的拦截器 -->
  17. <interceptors>
  18. <interceptor-stack name="myStack">
  19. <!-- 配置上传的拦截器 -->
  20. <interceptor-ref name="fileUpload">
  21. <!-- 限制上传的文件类型,这里限制为只能上传各种图片类型 -->
  22. <!--<param name="allowedTypes">image/bmp,image/png,image/jpg,image/jpeg</param>-->
  23. <!-- 限制上传文件的大小(单位是字节)-->
  24. <!--<param name="maximumSize">2097152</param>-->
  25. </interceptor-ref>
  26. <!-- 引用默认的拦截器栈 -->
  27. <interceptor-ref name="defaultStack"/>
  28. </interceptor-stack>
  29. </interceptors>
  30.  
  31. <!-- 普通上传 -->
  32. <action name="upload" class="org.demo02.action.DemoAction" method="upload">
  33. <!-- 引用拦截器 -->
  34. <interceptor-ref name="myStack"/>
  35. <!-- 上传成功后跳转的页面 -->
  36. <result>index.jsp</result>
  37.  
  38. <!-- 上传失败或有错误的提示页面,
  39. name="input"表示当有错误信息的时候要跳转到的提示页面-->
  40. <result name="input">upload.jsp</result>
  41. </action>
  42.  
  43. <!-- ajax上传,后台的上传方法是一样的,不同的是result的配置 -->
  44. <action name="ajaxUpload" class="org.demo02.action.DemoAction" method="upload">
  45. <!-- 引用拦截器 -->
  46. <interceptor-ref name="myStack"/>
  47. <result type="json">
  48. <param name="root">message</param>
  49. </result>
  50. <!-- 使用json结果集类型返回错误信息,用于ajax请求
  51. struts会将fieldErrors序列化成json对象 -->
  52. <result name="input" type="json">
  53. <param name="root">fieldErrors</param>
  54. </result>
  55. </action>
  56.  
  57. <!-- 文件下载 -->
  58. <action name="download" class="org.demo02.action.DownloadAction" method="download">
  59. <!-- 文件下载的结果集类型使用stream,表示一个流 -->
  60. <result type="stream">
  61. <!-- 设置一些下载的参数配置 -->
  62. <!-- contentType表示设置response的响应类型,这里设置为流类型 -->
  63. <param name="contentType">application/octet-stream</param>
  64. <!-- contentDisposition指定响应回客户端的下载的文件名,
  65. ${fileName}引用action中定义的fileName属性-->
  66. <param name="contentDisposition">attachment;filename="${fileName}"</param>
  67. <!-- inputName指定action中定义的getXxx方法,去掉get并将首字母改成小写 -->
  68. <param name="inputName">inputStream</param>
  69. <!-- 下载文件的缓冲大小(可选) -->
  70. <param name="bufferSize">4096</param>
  71. </result>
  72. </action>
  73. </package>
  74. </struts>

1.4.2 显示错误信息中文提示的:message.properties

  1. struts.messages.error.content.type.not.allowed = 不是允许的上传类型
  2. struts.messages.error.file.too.large = 已超出文件的限制大小

1.4.3文件上传的action:DemoAction

  1. package org.demo02.action;
  2.  
  3. import com.opensymphony.xwork2.ActionSupport;
  4. import org.apache.commons.io.FileUtils;
  5. import org.apache.struts2.ServletActionContext;
  6.  
  7. import java.io.File;
  8. import java.io.IOException;
  9.  
  10. /**
  11. * Created by YongLin on 17/2/9.
  12. */
  13. public class DemoAction extends ActionSupport {
  14. //表单文本数据
  15. private String readme;
  16.  
  17. //表单文件,必须是一个File类型
  18. private File uploadFile;
  19. //上传的文件名,格式必须是File名称 + FileName
  20. private String uploadFileFileName;
  21. //上传的文件类型,格式必须是File名称 + ContentType
  22. private String uploadFileContentType;
  23.  
  24. private String message;
  25.  
  26. public String getReadme() {
  27. return readme;
  28. }
  29.  
  30. public void setReadme(String readme) {
  31. this.readme = readme;
  32. }
  33.  
  34. public File getUploadFile() {
  35. return uploadFile;
  36. }
  37.  
  38. public void setUploadFile(File uploadFile) {
  39. this.uploadFile = uploadFile;
  40. }
  41.  
  42. public String getUploadFileFileName() {
  43. return uploadFileFileName;
  44. }
  45.  
  46. public void setUploadFileFileName(String uploadFileFileName) {
  47. this.uploadFileFileName = uploadFileFileName;
  48. }
  49.  
  50. public String getUploadFileContentType() {
  51. return uploadFileContentType;
  52. }
  53.  
  54. public void setUploadFileContentType(String uploadFileContentType) {
  55. this.uploadFileContentType = uploadFileContentType;
  56. }
  57.  
  58. public String getMessage() {
  59. return message;
  60. }
  61.  
  62. public void setMessage(String message) {
  63. this.message = message;
  64. }
  65.  
  66. //上传
  67. public String upload() throws IOException {
  68. //获取上传的绝对路径
  69. String uploadPath = ServletActionContext.getServletContext().getRealPath("/files");
  70. //如果提交过来的File不为null,才执行上传操作
  71. if(uploadFile != null){
  72. System.out.println(uploadFileFileName);
  73. System.out.println(uploadFileContentType);
  74. //根据文件名以及上传的路径构建一个新的File对象
  75. File saveFile = new File(uploadPath, uploadFileFileName);
  76. //先判断上传的目录是否存在,如果不存在则创建出来
  77. if(!saveFile.getParentFile().exists()){
  78. saveFile.getParentFile().mkdirs();
  79. }
  80. //使用文件复制执行上传
  81. FileUtils.copyFile(uploadFile, saveFile);
  82. //提示成功信息
  83. message = "上传成功";
  84. }
  85. return "success";
  86. }
  87. }

1.4.4 文件下载的action:DownloadAction

  1. package org.demo02.action;
  2.  
  3. import com.opensymphony.xwork2.ActionSupport;
  4. import org.apache.struts2.ServletActionContext;
  5.  
  6. import java.io.*;
  7.  
  8. /**
  9. * Created by YongLin on 17/2/10.
  10. */
  11. public class DownloadAction extends ActionSupport {
  12.  
  13. //要下载的文件名
  14. private String fileName;
  15.  
  16. public String getFileName() {
  17. //解决下载文件时中文名时出现乱码
  18. try {
  19. fileName = new String(fileName.getBytes("utf-8"),
  20. "ISO8859-1");
  21. } catch (UnsupportedEncodingException e) {
  22. e.printStackTrace();
  23. }
  24. return fileName;
  25. }
  26.  
  27. public void setFileName(String fileName) {
  28. this.fileName = fileName;
  29. }
  30.  
  31. //我们需要提供一个方法,这个方法是一个标准的get方法,如getXxx
  32. //并通过这个方法创建并返回一个InputStream给struts
  33. //struts就会根据这个输入流读取文件,并写回客户端
  34. public InputStream getInputStream() throws Exception {
  35. //获取文件上传的目录
  36. String uploadPath = ServletActionContext.getServletContext().getRealPath("/files");
  37. //根据路径结合提交过来的文件名,创建一个File对象
  38. File file = new File(uploadPath, fileName);
  39. //创建InputStream对象
  40. BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
  41. //返回这个输入流给struts
  42. return inputStream;
  43. }
  44.  
  45. public String download(){
  46. return "success";
  47. }
  48.  
  49. }
  1. 1.4.5Web.xml文件
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  5. version="3.1">
  6.  
  7. <filter>
  8. <filter-name>dispatcher</filter-name>
  9. <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  10. </filter>
  11. <filter-mapping>
  12. <filter-name>dispatcher</filter-name>
  13. <url-pattern>/*</url-pattern>
  14. </filter-mapping>
  15.  
  16. </web-app>

1.5.1index.jsp页面

  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: YongLin
  4. Date: 2017/2/9
  5. Time: 下午2:44
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9. <%@ taglib prefix="s" uri="/struts-tags" %>
  10. <html>
  11. <head>
  12. <title>Index</title>
  13. </head>
  14. <body>
  15. <!-- 显示文件名,并可以执行下载操作 -->
  16. <a href="download?fileName=<s:property value='uploadFileFileName'/>"><s:property value="uploadFileFileName"/></a>
  17. </body>
  18. </html>

1.5.2Ajax 文件上传(需要引入jQery包)

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <script src="js/jquery-1.9.1.min.js"></script>
  7. <script>
  8. $(function(){
  9. $("#btn").on("click",function(){
  10. //使用FormData来实现表单的封装和ajax上传
  11. var formData = new FormData(document.getElementById("f1"));
  12. //使用jquery的ajax提交表单
  13. $.ajax({
  14. url : "ajaxUpload", //请求的url
  15. type : "post", //请求类型
  16. data : formData, //表单数据
  17. processData : false, //让Jquery不处理发送的数据
  18. contentType : false, //让Jquery不设置Content-Type请求头
  19. success : function(result){ // 成功响应后的回调函数
  20. if(result.uploadFile != undefined){
  21. $("#msg").append("<font color='red'>"+result.uploadFile+"</font>");
  22. }else{
  23. $("#msg").append("<font color='red'>"+result+"</font>");
  24. }
  25. }
  26. });
  27. });
  28. });
  29. </script>
  30. </head>
  31. <body>
  32. <div id="msg"></div>
  33. <form id="f1" method="post" action="upload" enctype="multipart/form-data">
  34. File:<input type="file" name="uploadFile"/><br/>
  35. Readme:<input type="text" name="readme"/><br/>
  36. <input id="btn" type="button" value="button"/>
  37. </form>
  38. </body>
  39. </html>

1.6.1运行效果:

1.

点击提交  文件上传成功过后来到index.jsp页面

在页面中显示出文件名

2.

3.

4.Ajax文件上传

1.7.1Demo整体架构

1.8实例下载

Struts2学习总结——文件上传与下载的更多相关文章

  1. Struts2 之 实现文件上传和下载

    Struts2  之 实现文件上传和下载 必须要引入的jar commons-fileupload-1.3.1.jar commons-io-2.2.jar 01.文件上传需要分别在struts.xm ...

  2. JavaWeb学习总结——文件上传和下载

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...

  3. javaWeb学习总结——文件上传、下载

    目录 1.文件上传环境搭建 2.文件上传代码实现 3.关于下载 @ 嘿,熊dei,你不得不知道在Web开发中,文件上传和下载功能是非常常用的功能,关于文件上传,浏览器上传[文件以流的形式传输]--&g ...

  4. struts2中的文件上传和下载

    天下大事,必做于细.天下难事,必作于易. 以前见过某些人,基础的知识还不扎实就去学习更难的事,这样必定在学习新的知识会非常迷惑结果 再回来又一次学习一下没有搞懂的知识,这必定会导致学习效率的下降!我写 ...

  5. 4.struts2中的文件上传,下载

    Struts2中文件的上传下载,是借用commons里面的包实现文件的上传,需要导入两个jar commons-fileupload-1.2.2.jar commons-io-2.0.1.jar 实现 ...

  6. 1.6(Spring MVC学习笔记)文件上传与下载

    一.文件上传 实现文件上传多数是采用表单提交数据, 但对于进行文件上传的表单需要满足一下几个条件 1.表单的method设置为post 2.表单的enctype设置为multipart/form-da ...

  7. 16.Django学习之文件上传和下载

    上传就这么六步! 一. settings配置文件中配置 MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'medias').repl ...

  8. Struts2 之 实现文件上传(多文件)和下载

    Struts2  之 实现文件上传和下载 必须要引入的jar commons-fileupload-1.3.1.jar commons-io-2.2.jar 01.文件上传需要分别在struts.xm ...

  9. 【SSH2(实用文章)】--Struts2文件上传和下载的例子

    回想一下,再上一篇文章Struts2实现机制,该步骤做一步一步来解决,这种决心不仅要理清再次Struts2用法.映射机制及其在深入分析.最后一个例子来介绍Struts2一种用法,这里将做一个有关文件上 ...

随机推荐

  1. Bash拾遗:变量

    使用引号包裹变量 在<高级Bash脚本编程指南>中的4.1节中有这么个例子: hello="A B C D" echo $hello # A B C D echo &q ...

  2. Luogu3307:[SDOI2013]项链

    传送门 求每个珠子的方案数 即有序的求三元组 \((x,y,z),x,y,z\le a\) 满足 \(gcd(x,y,z)=1\) 设 \(G_i\) 表示 \(i\) 个小于等于 \(a\) 的有序 ...

  3. angular排序

    说点小案例angular的排序 <!DOCTYPE html> <html ng-app="mk"> <head> <meta chars ...

  4. oracle基础-创建表空间

    一. 创建表空间的完整格式 CREATE [UNDO|TEMPORARY] TABLESPACE tablespace_name       DATAFILE 'path/filename' [SIZ ...

  5. LoadRunner对移动互联网后端服务器压力测试

    一.LoadRunner简介 LoadRunner,是惠普公司研发的一款预测系统行为和性能的负载测试工具.通过以模拟上千万用户实施并发负载及实时性能监测的方式来确认和查找问题,LoadRunner能够 ...

  6. 用jsp实现网站登录界面的制作,并连接数据库

    课堂测试 任务需求: 撰写一篇博客 需要网站系统开发需要掌握的技术: 本次课堂测试的源程序代码: 运行结果截图: 说明课堂测试未按时完成的原因. 列出你对这门课的希望和自己的目标,并具体列出你计划每周 ...

  7. 【 PostgreSQL】工作中常用SQL语句干货

    接触gp数据库近一年的时间,语法上和其他数据库还是有些许不同,工作中常用的操作语句分享给大家! -- 建表语句 create table ods.ods_b_bill_m ( acct_month t ...

  8. margin的用法

    margin塌陷问题 当时说到了盒模型,盒模型包含着margin,为什么要在这里说margin呢?因为元素和元素在垂直方向上margin里面有坑. 我们来看一个例子: html结构: <div ...

  9. [翻译] ASCScreenBrightnessDetector

    ASCScreenBrightnessDetector ASCScreenBrightnessDetector lets you easily detect screen brightness cha ...

  10. Handlebars.js中集合(list)通过中括号的方式取值

    有这么一个需求,在一个table中,tr是通过each取值,取出的值要与table标题相对应,如何实现?例如: <table> <thead> <tr> {{#ea ...