原文地址:http://blog.csdn.net/java_cxrs/article/details/6004144

描述:

通过struts2实现多图片上传。

我使用的版本是2.2.1,使用的包有如下几个:

具体实现:

1.创建上传图片的页面

fileUpload.jsp   

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2.  
  3. <%@ taglib prefix="s" uri="/struts-tags" %>
  4.  
  5. <%
  6.  
  7. String path = request.getContextPath();
  8.  
  9. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  10.  
  11. %>
  12.  
  13. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  14.  
  15. <html>
  16.  
  17. <head>
  18.  
  19. <base href="<%=basePath%>">
  20.  
  21. <title>My JSP 'fileUpLoad.jsp' starting page</title>
  22.  
  23. <meta http-equiv="pragma" content="no-cache">
  24.  
  25. <meta http-equiv="cache-control" content="no-cache">
  26.  
  27. <meta http-equiv="expires" content="0">
  28.  
  29. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  30.  
  31. <meta http-equiv="description" content="This is my page">
  32.  
  33. <!--
  34.  
  35. <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
  36.  
  37. -->
  38.  
  39. </head>
  40.  
  41. <body>
  42.  
  43. <center>
  44.  
  45. <s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data" >
  46.  
  47. <s:fielderror />
  48.  
  49. <s:file name ="myFile" label ="Image File1"/>
  50.  
  51. <s:file name ="myFile" label ="Image File2"/>
  52.  
  53. <s:file name ="myFile" label ="Image File3"/>
  54.  
  55. <s:textfield name ="caption" label ="Caption" />
  56.  
  57. <s:submit/>
  58.  
  59. </s:form>
  60.  
  61. </center>
  62.  
  63. </body>
  64.  
  65. </html>

在FileUpload.jsp中,先将表单的提交方式设为POST,然后将enctype设为multipart/form-data,这并没有什么特别之处。接下来,<s:file/>标志将文件上传控件绑定到Action的myFile属性,因为要上传多张图片我们就暂且添加三个file

注意这三个file的name属性要相同。

  2.创建处理图片上传的action

FileUploadAction.java

  1. package com.ywjava.action;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.BufferedOutputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.FileOutputStream;
  8. import java.io.InputStream;
  9. import java.io.OutputStream;
  10. import java.util.ArrayList;
  11. import java.util.Date;
  12. import java.util.List;
  13.  
  14. import org.apache.struts2.ServletActionContext;
  15.  
  16. import com.opensymphony.xwork2.ActionSupport;
  17.  
  18. public class FileUploadAction extends ActionSupport {
  19. private static final long serialVersionUID = 572146812454l;
  20. private static final int BUFFER_SIZE = 16 * 1024;
  21. private List<File> myFile = new ArrayList<File>();
  22. private List<String> contentType = new ArrayList<String>();
  23. private List<String> fileName = new ArrayList<String>(); //文件名
  24. private List<String> imageFileName = new ArrayList<String>();
  25. private String caption;
  26.  
  27. private static void copy(File src, File dst) {
  28. try {
  29. InputStream in = null;
  30. OutputStream out = null;
  31. try {
  32. in = new BufferedInputStream(new FileInputStream(src),
  33. BUFFER_SIZE);
  34. out = new BufferedOutputStream(new FileOutputStream(dst),
  35. BUFFER_SIZE);
  36. byte[] buffer = new byte[BUFFER_SIZE];
  37. while (in.read(buffer) > 0) {
  38. out.write(buffer);
  39. }
  40. } finally {
  41. if (null != in) {
  42. in.close();
  43. }
  44. if (null != out) {
  45. out.close();
  46. }
  47. }
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. }
  51. }
  52.  
  53. private static String getExtention(String fileName) {
  54. int pos = fileName.lastIndexOf(".");
  55. return fileName.substring(pos);
  56. }
  57.  
  58. @Override
  59. public String execute() {
  60. if (myFile == null)
  61. return INPUT;
  62. for (int i = 0; i < myFile.size(); i++) {
  63. imageFileName.add(new Date().getTime()+ getExtention(this.getMyFileFileName().get(i))) ;
  64. File imageFile = new File(ServletActionContext.getServletContext() //得到图片保存的位置(根据root来得到图片保存的路径在tomcat下的该工程里)
  65.  
  66. .getRealPath("UploadImages")
  67. + "/" + imageFileName);
  68. copy(myFile.get(i), imageFile); //把图片写入到上面设置的路径里
  69.  
  70. }
  71. return SUCCESS;
  72. }
  73.  
  74. public List<File> getMyFile() {
  75. return myFile;
  76. }
  77.  
  78. public void setMyFile(List<File> myFile) {
  79. this.myFile = myFile;
  80. }
  81.  
  82. public List<String> getContentType() {
  83. return contentType;
  84. }
  85.  
  86. public void setContentType(List<String> contentType) {
  87. this.contentType = contentType;
  88. }
  89.  
  90. public List<String> getMyFileFileName() {
  91. return fileName;
  92. }
  93.  
  94. public void setMyFileFileName(List<String> fileName) {
  95. this.fileName = fileName;
  96. }
  97.  
  98. public List<String> getImageFileName() {
  99. return imageFileName;
  100. }
  101.  
  102. public void setImageFileName(List<String> imageFileName) {
  103. this.imageFileName = imageFileName;
  104. }
  105.  
  106. public String getCaption() {
  107. return caption;
  108. }
  109.  
  110. public void setCaption(String caption) {
  111. this.caption = caption;
  112. }
  113.  
  114. public static int getBufferSize() {
  115. return BUFFER_SIZE;
  116. }
  117.  
  118. }

在FileUploadAction中我分别写了setMyFileContentType、setMyFileFileName、setMyFile和setCaption四个Setter方法,

后两者很容易明白,分别对应FileUpload.jsp中的<s:file/>和<s:textfield/>标志。但是前两者并没有显式地与任何的页面标志绑定,

那么它们的值又是从何而来的呢?其实,<s:file/>标志不仅仅是绑定到myFile,

还有myFileContentType(上传文件的MIME类型)和myFileFileName(上传文件的文件名,该文件名不包括文件的路径)。

因此,<s:file name="xxx" />对应Action类里面的xxx、xxxContentType和xxxFileName三个属性。

FileUploadAction作用是将浏览器上传的文件拷贝到WEB应用程序的

UploadImages文件夹下,新文件的名称是由系统时间与上传文件的后缀组成,

该名称将被赋给imageFileName属性,以便上传成功的跳转页面使用。

  3.创建显示图片的页面

showUpload.jsp

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2. <%@ taglib prefix="s" uri="/struts-tags" %>
  3. <%
  4. String path = request.getContextPath();
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  6. %>
  7.  
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  9. <html>
  10. <head>
  11. <base href="<%=basePath%>">
  12.  
  13. <title>Show Image</title>
  14.  
  15. <meta http-equiv="pragma" content="no-cache">
  16. <meta http-equiv="cache-control" content="no-cache">
  17. <meta http-equiv="expires" content="0">
  18. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  19. <meta http-equiv="description" content="This is my page">
  20. <!--
  21. <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
  22. -->
  23.  
  24. </head>
  25.  
  26. <body>
  27. <s:iterator value="imageFileName" status="length">
  28.  
  29. <div
  30. style="padding: 3px; border: solid 1px #cccccc; text-align: center">
  31. <img src='UploadImages/<s:property value ="imageFileName" /> ' />
  32. <br />
  33. <s:property value="caption" />
  34. </div>
  35. </s:iterator>
  36. <s:property value ="caption" />
  37.  
  38. </body>
  39. </html>

4.Action配置文件

Struts.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE struts PUBLIC
  3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  4. "http://struts.apache.org/dtds/struts-2.0.dtd">
  5.  
  6. <struts>
  7.  
  8. <constant name="struts.enable.DynamicMethodInvocation" value="false" />
  9. <constant name="struts.devMode" value="false" />
  10.  
  11. <!-- 指定国际化资源文件的baseName为messageResource -->
  12. <constant name="struts.custom.i18n.resources" value="messageResource" />
  13.  
  14. <!-- 设置该应用使用的解码集 -->
  15. <constant name="struts.i18n.encoding" value="utf-8" />
  16.  
  17. <!-- 上传的全部图片的最大限制-->
  18. <constant name="struts.multipart.maxSize" value="1024102400" />
  19.  
  20. <!-- 临时存放文件的路径 -->
  21. <constant name="struts.multipart.saveDir" value="d:/test" />
  22.  
  23. <package name="index" namespace="/" extends="struts-default">
  24.  
  25. <action name="index" class="com.ywjava.action.IndexAction">
  26. <result>
  27. /WEB-INF/page/fileUpLoad.jsp
  28. </result>
  29. </action>
  30.  
  31. <action name="fileUpload" class="com.ywjava.action.FileUploadAction">
  32. <!-- 限制图片的格式和图片的大小 -->
  33. <interceptor-ref name="fileUpload">
  34. <param name="allowedTypes">
  35. image/bmp,image/png,image/gif,image/jpeg,image/pjpeg
  36. </param>
  37. </interceptor-ref>
  38. <!-- 默认的拦截器,必须要写 -->
  39. <interceptor-ref name="defaultStack" />
  40. <result name="input"> /WEB-INF/page/fileUpLoad.jsp</result>
  41. <result name="success">/WEB-INF/page/showUpload.jsp</result>
  42.  
  43. </action>
  44. </package>
  45. <!--
  46. <constant name="struts.multipart.saveDir" value="d:/test"></constant>
  47. -->
  48.  
  49. <!-- Add packages here -->
  50.  
  51. </struts>

Action配置文件里所做的配置都有注释,不明白的地方看下注释

另外因为做了国际化处理所以需要一个国际化配置的文件

放在src目录下

5.国际化配置文件

messageResource_zh_CN.properties(只配置了中文的)

struts.messages.error.content.type.not.allowed=/u4E0A/u4F20/u7C7B/u578B/u9519/u8BEF

struts.messages.error.file.too.large=/u4E0A/u4F20/u6587/u4EF6/u592A/u5927

总结:struts2上传图片利用了fileUpload拦截器而变的简单,主要是在action中做相应处理获取文件的相应信息。

struts2多图片上传实例【转】的更多相关文章

  1. PHP多图片上传实例demo

    upload.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:/ ...

  2. Thinkphp整合阿里云OSS图片上传实例

    Thinkphp3.2整合阿里云OSS图片上传实例,图片上传至OSS可减少服务器压力,节省宽带,安全又稳定,阿里云OSS对于做负载均衡非常方便,不用传到各个服务器了 首先引入阿里云OSS类库 < ...

  3. PHP结合zyupload多功能图片上传实例

    PHP结合zyupload多功能图片上传实例,支持拖拽和裁剪.可以自定义高度和宽度,类型,远程上传地址等. zyupload上传基本配置 $("#zyupload").zyUplo ...

  4. PHP 多图片上传实例demo

    upload.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:/ ...

  5. layui加tp5图片上传实例

    <div class="layui-fluid"> <div class="layui-row"> <form class=&qu ...

  6. webuploader项目中多图片上传实例

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...

  7. 使用Struts2实现图片上传和拦截器

    今天来分享一个图片上传 现在很多小项目里面基本上都有要显示图片的功能,所以呢图片上传是基本要掌握的啦 一般的图片上传原理就是从本地选择一张图片然后通过io流发布到服务器上去 上传方案基本有三种: 1. ...

  8. asp.net图片上传实例

    网站后台都需要有上传图片的功能,下面的例子就是实现有关图片上传. 缺点:图片上传到本服务器上,不适合大量图片上传. 第一.图片上传,代码如下: xxx.aspx 复制代码代码如下: <td cl ...

  9. Thinkphp框架图片上传实例

     https://www.cnblogs.com/wupeiky/p/5802191.html    [原文转载自:https://www.cnblogs.com/guoyachao/p/628286 ...

随机推荐

  1. 提高CPU使用率

    某些特殊时候,需要提升下cpu的利用率,此时……………………需要一个极其简单的脚本来完成! #!/bin/bash while (true);do { for i in $(seq 100000 10 ...

  2. 4. COLLATION_CHARACTER_SET_APPLICABILITY

    4. COLLATION_CHARACTER_SET_APPLICABILITY 表COLLATION_CHARACTER_SET_APPLICABILITY表示哪种字符集适用于哪种排序规则. INF ...

  3. RHEL6.5 DHCP服务器搭建

    RHEL6.5 DHCP服务器搭建: DHCP服务器是用来分配给其它客户端IP地址用的,在RHEL 6.5中DHCP服务器搭建方法如下: 第一步,通过yum安装dhcp服务: 命令:yum insta ...

  4. 如何用纯 CSS 创作一种侧立图书的特效

    效果预览 在线演示 按下右侧的"点击预览"按钮在当前页面预览,点击链接全屏预览. https://codepen.io/zhang-ou/pen/deVgRM 可交互视频教程 此视 ...

  5. NBUT 1651 - Red packet (求运气王的钱数)(二分法)

    Description New Year is coming! Our big boss Wine93 will distribute some “Red Package”, just like Al ...

  6. notepad++编辑器写python需注意使用utf-8编码

    语言:python3.4 文本编辑器:notepad++ 报错:SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xb4 in ...

  7. Go循环语句

    package main import ( "fmt" "strconv" "os" "bufio" ) //for的条 ...

  8. POJ 2002 几何+hash

    题目大意: 给定1000个点,寻找有多少组四点对能组成正方形 这里的题目跟上一道做的找平行四边形类似但想法却又不相同的方法 这里找任意2个点形成的一条边,那么可以根据这两个点,找到能和他们组成正方形剩 ...

  9. Python基础之 一 文件操作

    文件操作 流程: 1:打开文件,得到文件句柄并赋值给一个变量 2:通过句柄对文件进行操作 3:关闭文件 模式解释 r(读) , w(写) ,a(附加)r+(读写的读), w+(读写的写),a+(读附加 ...

  10. HUNAN 11567 Escaping (最大流)

    http://acm.hunnu.edu.cn/online/?action=problem&type=list&courseid=0&querytext=&pagen ...