当前位置: 移动技术网 > IT编程>开发语言>Java > JavaWeb中struts2实现文件上传下载功能实例解析

JavaWeb中struts2实现文件上传下载功能实例解析

2019年07月22日  | 移动技术网IT编程  | 我要评论

在做b/s系统时,通常会涉及到上传文件和下载文件,在没接struts2框架之前,我们都是使用apache下面的commons子项目的fileupload组件来进行文件的上传,但是那样做的话,代码看起来比较繁琐,而且不灵活,在学习了struts2后,struts2为文件上传下载提供了更好的实现机制,在这里我分别就单文件上传和多文件上传的源代码进行一下讲解,这里需要导入文件下载上传的两个jar文件,一个是commons-fileupload-1.2.2.jar,另一个是commons-io-2.0.1.jar

struts2单文件上传:

首先是一个jsp文件上传页面,这个比较简单,就是一个表单,里面有个文件上传框

  <!--在进行文件上传时,表单提交方式一定要是post的方式,因为文件上传时二进制文件可能会很大,还有就是enctype属性,这个属性一定要写成multipart/form-data,
  不然就会以二进制文本上传到服务器端--> 
  <form action="fileupload.action" method="post" enctype="multipart/form-data">
    
    username: <input type="text" name="username"><br>
    file: <input type="file" name="file"><br>
    
    <input type="submit" value="submit">
  </form>

接下来是fileuploadaction部分代码,因为struts2对上传和下载都提供了很好的实习机制,所以在action这段我们只需要写很少的代码就行:

public class fileuploadaction extends actionsupport
{
  private string username;
  
   //注意,file并不是指前端jsp上传过来的文件本身,而是文件上传过来存放在临时文件夹下面的文件
  private file file;
  
  //提交过来的file的名字
  private string filefilename;
  
  //提交过来的file的mime类型
  private string filecontenttype;

  public string getusername()
  {
    return username;
  }

  public void setusername(string username)
  {
    this.username = username;
  }

  public file getfile()
  {
    return file;
  }

  public void setfile(file file)
  {
    this.file = file;
  }

  public string getfilefilename()
  {
    return filefilename;
  }

  public void setfilefilename(string filefilename)
  {
    this.filefilename = filefilename;
  }

  public string getfilecontenttype()
  {
    return filecontenttype;
  }

  public void setfilecontenttype(string filecontenttype)
  {
    this.filecontenttype = filecontenttype;
  }
  
  @override
  public string execute() throws exception
  {
    string root = servletactioncontext.getservletcontext().getrealpath("/upload");
    
    inputstream is = new fileinputstream(file);
    
    outputstream os = new fileoutputstream(new file(root, filefilename));
    
    system.out.println("filefilename: " + filefilename);

    // 因为file是存放在临时文件夹的文件,我们可以将其文件名和文件路径打印出来,看和之前的filefilename是否相同
    system.out.println("file: " + file.getname());
    system.out.println("file: " + file.getpath());
    
    byte[] buffer = new byte[500];
    int length = 0;
    
    while(-1 != (length = is.read(buffer, 0, buffer.length)))
    {
      os.write(buffer);
    }
    
    os.close();
    is.close();
    
    return success;
  }
}

首先我们要清楚一点,这里的file并不是真正指代jsp上传过来的文件,当文件上传过来时,struts2首先会寻找struts.multipart.savedir(这个是在default.properties里面有)这个name所指定的存放位置,我们可以新建一个struts.properties属性文件来指定这个临时文件存放位置,如果没有指定,那么文件会存放在tomcat的apache-tomcat-7.0.29\work\catalina\localhost\目录下,然后我们可以指定文件上传后的存放位置,通过输出流将其写到流里面就行了,这时我们就可以在文件夹里看到我们上传的文件了。

文件上传后我们还需要将其下载下来,其实struts2的文件下载原理很简单,就是定义一个输入流,然后将文件写到输入流里面就行,关键配置还是在struts.xml这个配置文件里配置:

filedownloadaction代码如下:

public class filedownloadaction extends actionsupport
{
  public inputstream getdownloadfile()
  {
    return servletactioncontext.getservletcontext().getresourceasstream("upload/通讯录2012年9月4日.xls");
  }
  
  @override
  public string execute() throws exception
  {
    return success;
  }
}

我们看,这个action只是定义了一个输入流,然后为其提供getter方法就行,接下来我们看看struts.xml的配置文件:

    <action name="filedownload" class="com.xiaoluo.struts2.filedownloadaction">
      <result name="success" type="stream">
        <param name="contentdisposition">attachment;filename="通讯录2012年9月4日.xls"</param>
        <param name="inputname">downloadfile</param>
      </result>
    </action>

struts.xml配置文件有几个地方我们要注意,首先是result的类型,以前我们定义一个action,result那里我们基本上都不写type属性,因为其默认是请求转发(dispatcher)的方式,除了这个属性一般还有redirect(重定向)等这些值,在这里因为我们用的是文件下载,所以type一定要定义成stream类型,告诉action这是文件下载的result,result元素里面一般还有param子元素,这个是用来设定文件下载时的参数,inputname这个属性就是得到action中的文件输入流,名字一定要和action中的输入流属性名字相同,然后就是contentdisposition属性,这个属性一般用来指定我们希望通过怎么样的方式来处理下载的文件,如果值是attachment,则会弹出一个下载框,让用户选择是否下载,如果不设定这个值,那么浏览器会首先查看自己能否打开下载的文件,如果能,就会直接打开所下载的文件,(这当然不是我们所需要的),另外一个值就是filename这个就是文件在下载时所提示的文件下载名字。在配置完这些信息后,我们就能过实现文件的下载功能了。

struts2多文件上传

其实多文件上传和单文件上传原理一样,单文件上传过去的是单一的file,多文件上传过去的就是一个list<file>集合或者是一个file[]数组,首先我们来看一下前端jsp部分的代码,这里我用到了jquery来实现动态的添加文件下载框以及动态的删除下载框:

  <script type="text/javascript" src="script/jquery-1.8.1.js"></script>
  <script type="text/javascript">
      
    $(function()
    {
      $("#button").click(function()
      {
        var html = $("<input type='file' name='file'>");
        var button = $("<input type='button' name='button' value='删除'><br>");
        
        $("#body div").append(html).append(button);
        
        button.click(function()
        {
          html.remove();
          button.remove();
        })
      })
    })
  
  </script>
 </head>
 
 <body id="body">

  <form action="fileupload2.action" method="post" enctype="multipart/form-data">
  
    username: <input type="text" name="username"><br>
    file: <input type="file" name="file">
    <input type="button" value="添加" id="button"><br>
    <div></div>
    <input type="submit" value="submit"> 
    
  </form>

 </body>

file的名字必须都命名成file才行,然后处理多文件上传的action代码如下:

public class fileuploadaction2 extends actionsupport
{
  private string username;
  
  //这里用list来存放上传过来的文件,file同样指的是临时文件夹中的临时文件,而不是真正上传过来的文件
  private list<file> file;
  
  //这个list存放的是文件的名字,和list<file>中的文件相对应
  private list<string> filefilename;
  
  private list<string> filecontenttype;

  public string getusername()
  {
    return username;
  }

  public void setusername(string username)
  {
    this.username = username;
  }

  public list<file> getfile()
  {
    return file;
  }

  public void setfile(list<file> file)
  {
    this.file = file;
  }

  public list<string> getfilefilename()
  {
    return filefilename;
  }

  public void setfilefilename(list<string> filefilename)
  {
    this.filefilename = filefilename;
  }

  public list<string> getfilecontenttype()
  {
    return filecontenttype;
  }

  public void setfilecontenttype(list<string> filecontenttype)
  {
    this.filecontenttype = filecontenttype;
  }
  
  @override
  public string execute() throws exception
  {
    string root = servletactioncontext.getservletcontext().getrealpath("/upload");
    
    for(int i = 0; i < file.size(); i++)
    {
      inputstream is = new fileinputstream(file.get(i));
      
      outputstream os = new fileoutputstream(new file(root, filefilename.get(i)));
      
      byte[] buffer = new byte[500];
      
      @suppresswarnings("unused")
      int length = 0;
      
      while(-1 != (length = is.read(buffer, 0, buffer.length)))
      {
        os.write(buffer);
      }
      
      os.close();
      is.close();
    }
    
    return success;
  }
}

这样同样将其写到一个输出流里面,这样我们就可以在文件夹里看到上传的多个文件了

接下来的文件下载就和刚才的文件下载一模一样,struts.xml也是一样的,这里就不再重复了

总结:总的来说,struts2提供的文件上传下载机制简化了我们很多代码,我们可以在以后的项目中使用该机制,同样我们也可以使用fileupload组件来进行文件的上传,这个都是因个人爱好决定!

关于javaweb中的文件上传和下载功能的内容就这么多,谢谢大家的阅读。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网