灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:2867回复:0

Struts2实现文件上传

楼主#
更多 发布于:2012-09-08 09:35

文件上传这个功能是很多网站都要有的,当然,Struts对文件上传也进了支持,可以

说,使用Struts实现文件上传是非常简单的而且方便,下面来介绍一下。

首先,需要导入包commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar,后面的那

个包是因为在下面的代码中会使用到它里面的一些方法,实际上也可以不加入,这些包都

是可以在Struts的lib文件夹里面找到的.

然后就是写Action类了,这里需要接收文件(File类型),文件名,文件类型,文件名

必须和表单里面的name属性名一致,学过servlet的都知道为什么,然后文件名的写法是

文件名+FileName,然后文件类型名称的写法是文件名+ContentType,分别把他们设置成

属性,就是分别为他们提供set和get方法。

接着需要把接受到的File文件转存到服务器的目录里,否则它就存放在Struts的临时

目录里面,在Action执行完毕后会被删除。具体方法是使用servletContextgetRealPath

方法获得项目的绝对路径,然后建立一个目录去存放这个上传的文件。

代码如下

[java]
package com.bird.action;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

public class FileUpload {
    
    private File image;//获取上传文件  
    private String imageFileName;//获取上传文件名称  
    private String imageContentType;//获取上传文件类型  
    
    public String getImageContentType() {
        return imageContentType;
    }

    public void setImageContentType(String imageContentType) {
        this.imageContentType = imageContentType;
    }

    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }

    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    public String execute(){
        String path = ServletActionContext.getServletContext().getRealPath("/images");
        
        System.out.println(path);
        if(image != null){
        File savefile = new File(new File(path),imageFileName);
        if(!savefile.getParentFile().exists())
            savefile.getParentFile().mkdirs();
        try {
            FileUtils.copyFile(image , savefile);
        } catch (IOException e) {
            // TODO Auto-generated catch block  
            e.printStackTrace();
        }
          
        String[] t = imageContentType.split("/");
        for(String s : t)
            System.out.println(s);
        }
        return "success";
    }
}
package com.bird.action;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

public class FileUpload {
      
       private File image;//获取上传文件
       private String imageFileName;//获取上传文件名称
       private String imageContentType;//获取上传文件类型
      
       public String getImageContentType() {
              return imageContentType;
       }

       public void setImageContentType(String imageContentType) {
              this.imageContentType = imageContentType;
       }

       public File getImage() {
              return image;
       }

       public void setImage(File image) {
              this.image = image;
       }

       public String getImageFileName() {
              return imageFileName;
       }

       public void setImageFileName(String imageFileName) {
              this.imageFileName = imageFileName;
       }

       public String execute(){
              String path = ServletActionContext.getServletContext().getRealPath("/images");
            
              System.out.println(path);
              if(image != null){
              File savefile = new File(new File(path),imageFileName);
              if(!savefile.getParentFile().exists())
                     savefile.getParentFile().mkdirs();
              try {
                     FileUtils.copyFile(image , savefile);
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
            
              String[] t = imageContentType.split("/");
              for(String s : t)
                     System.out.println(s);
              }
              return "success";
       }
}

接着就是去注册这个Action,没有什么不同,不多说

[java]
<action name="fileupload" class="com.bird.action.FileUpload" method="execute">
        <result name="success">/index.jsp</result>
    </action>
</package>
       <action name="fileupload" class="com.bird.action.FileUpload" method="execute">
                     <result name="success">/index.jsp</result>
              </action>
       </package>
接着就是表单的提交,唯一需要注意的就是

form的enctype属性为编码方式,常用有两种:application/x-www-form-

urlencoded和multipart/form-data,默认为application/x-www-form-

urlencoded。

      当action为get时候,浏览器用x-www-form-urlencoded的编码方式把form数据

转换成一个字串(name1=value1;name2=value2...),然后把这个字串append到

url后面,用?分割,加载这个新的url。


当action为post时候,浏览器把form数据封装到http body中,然后发送到server。



如果没有type=file的控件,用默认的application/x-www-form-urlencoded就可以了。
但是如果有type=file的话,就要用到multipart/form-data了。浏览器会把整个表单以

控件为单位分割,并为每个部分加上Content-Disposition(form-data或者

file),Content-Type(默认为text/plain),name(控件name)等信息,并加上分割符

(boundary)。

下面是代码

[java]
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'fileUpload.jsp' starting page</title>
      
  </head>
  
  <body>
    
    <form action="${pageContext.request.contextPath }/test/fileupload.action" enctype="multipart/form-data" method="post">
        选择文件<input type="file" name="image">
        <input type="submit" value="上传">
    </form>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'fileUpload.jsp' starting page</title>
  
  </head>

  <body>
    
      <form action="${pageContext.request.contextPath }/test/fileupload.action" enctype="multipart/form-data" method="post">
             选择文件<input type="file" name="image">
             <input type="submit" value="上传">
      </form>
  </body>
</html>

另外一点需要注意的是,struts的默认上传文件大小为2M,所以为了扩大上传限制,下

面就得使用struts常量来限制了,具体如下

[java]
<constant name="struts.multipart.maxSize" value="104857600"></constant>
<constant name="struts.multipart.maxSize" value="104857600"></constant>
这样就设置上传最大为10M,当然,真正的视频门户网站会使用插件为不是这种web

传的方式上传文件,所以设置太大也没什么意义,那个上传插件其实就是使用Socket连

服务器指定端口进行上传,可以多线程等等,断点续传什么的,当然了,Web上传的

稳定性不行,所以一般不实用他上传较大文件



喜欢0 评分0
游客

返回顶部