zoukankan      html  css  js  c++  java
  • Struts2--文件上传与下载

      在Struts2里面提供了内置的处理文件上传的支持。在正确的配置好的前提下,上传的文件会被传到action里面去。支持单文件和多文件上传。当一个文件被上传的时候,会先把上传的文件存储到一个临时目录中,上传的文件可以通过action类来处理或者移到其他地方来保证数据不会丢失。

      Struts2使用附加的类库来处理文件的转换,需要我们单独加入到我们的project中

        |-Commons-FileUpload

        |-Commons-IO

      在defaultStack里面,包含了一个默认的类(org.apache.struts2.interceptor.FileUploadInterceptor)来处理文件上传。

      用来上传文件的表单,需要加上encoding的方式,如下代码:

    复制代码
    <%@ page language="java" pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>表单界面</title>
    </head>
    <body>
        <p>文件上传页面/p>
        <s:form action="doUpload" method="post" enctype="multipart/form-data">
            <s:file name="upload" label="文件"/>
            <s:submit value="上传"/>
        </s:form>
    </body>
    </html>
    复制代码

      在fileUpload拦截器会使用注入的方式把上传的文件关联到action类里面去。我们需要在action类里面提供以下三个setter方法。

    复制代码
    package com.fuwh.model;
    
    import java.io.File;
    import java.util.Date;
    
    import org.apache.commons.io.FileUtils;
    
    import com.opensymphony.xwork2.ActionSupport;
    import com.sun.jmx.snmp.Timestamp;
    
    public class UploadAction extends ActionSupport{
        
        private static final long serialVersionUID = 1L;
        
        //form表单里面的的文件名字要
        private File file;
        //form表单里面的的文件名字+FileName
        private String fileFileName;
        //form表单里面的的文件名字+ContentType
        private String fileContentType;
        
        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 {
            // TODO Auto-generated method stub
            System.out.println("default execute method!!!");
            System.out.println(file.getPath()+" "+file.getName());
            System.out.println(fileFileName);
            System.out.println(fileContentType);
            
            File destFile=new File("D:"+File.separator+fileFileName);
            System.out.println(destFile.getPath());
            //复制图片
            FileUtils.copyFile(file, destFile);
            
            return SUCCESS;
        }
        
        
    }
    复制代码

    配置文件代码

    复制代码
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
    
    <struts>
        <!-- 开启debug模式,会自动加载配置文件等等,不用每次更改了配置文件就去重新启动下服务器 -->
        <constant name="struts.devMode" value="true" />
        
        <!-- 配置action -->
        <package name="uploadAction" extends="struts-default">
            <action name="uploadAction" class="com.fuwh.model.UploadAction">
                <result name="success">success.jsp</result>
                <!-- 必须要有input -->
                <result name="input">index.jsp</result>
            </action>
        </package>
    
    </struts>
    复制代码

    上传多个文件

      当需要上传多个文件的时候,基本上和单个文件是一样的处理,首先在表单的地方写多个文件选择框。可以选择使用不同的名字,则在action类里面也写三个,系统就会处理三次文件的上传,还有一种选择就是在表单里面使用相同的名字,则在action类里面用一个文件数组的方式来接收。还可以选择使用List来接收

    array数组的方式

    复制代码
    <%@ page language="java" pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>表单界面</title>
    </head>
    <body>
        <p style="color: red">多个文件上传页面</p>
        <s:form action="uploadAction" method="post" enctype="multipart/form-data">
            <s:file name="file" label="文件1"/>
            <s:file name="file" label="文件2"/>
            <s:file name="file" label="文件3"/>
            <s:submit value="上传"/>
        </s:form>
    </body>
    </html>
    复制代码
    复制代码
    package com.fuwh.model;
    
    import java.io.File;
    
    import org.apache.commons.io.FileUtils;
    import com.opensymphony.xwork2.ActionSupport;
    
    public class UploadAction extends ActionSupport{
        
        private static final long serialVersionUID = 1L;
        
        //form表单里面的的文件名字要
        private File[] file;
        //form表单里面的的文件名字+FileName
        private String[] fileFileName;
        //form表单里面的的文件名字+ContentType
        private String[] fileContentType;
        
        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 {
            // TODO Auto-generated method stub
            for (int i = 0; i < file.length; i++) {
                File destFile=new File("D:"+File.separator+fileFileName[i]);
                System.out.println(destFile.getPath());
                //复制图片
                FileUtils.copyFile(file[i], destFile);
            }
            return SUCCESS;
        }
        
        
    }
    复制代码

    List的方式 

    复制代码
    package com.fuwh.model;
    
    import java.io.File;
    import java.util.List;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class UploadAction extends ActionSupport{
        
        private static final long serialVersionUID = 1L;
        
        //form表单里面的的文件名字要file
        private List<File> uploads;
        //form表单里面的的文件名字+FileName
        private List<String> uploadNames;
        //form表单里面的的文件名字+ContentType
        private List<String> uploadContentTypes;
    
        public List<File> getFile() {
            return uploads;
        }
    
        public void setFile(List<File> uploads) {
            this.uploads = uploads;
        }
    
        public List<String> getFileFileName() {
            return uploadNames;
        }
    
        public void setFileFileName(List<String> uploadNames) {
            this.uploadNames = uploadNames;
        }
    
        public List<String> getFileContentType() {
            return uploadContentTypes;
        }
    
        public void setFileContentType(List<String> uploadContentTypes) {
            this.uploadContentTypes = uploadContentTypes;
        }
    
        @Override
        public String execute() throws Exception {
            // TODO Auto-generated method stub
            for (File file : uploads) {
                System.out.println(file);
            }
            
            for (String string : uploadContentTypes) {
                System.out.println(string);
            }
            
            for (String string : uploadNames) {
                System.out.println(string);
            }
            return SUCCESS;
        }
        
    }
    复制代码

    文件下载

    复制代码
    <%@ page language="java" pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>表单界面</title>
    </head>
    <body>
        <a href="download1">文件下载1</a><br/>
        <a href="download2">文件下载2</a><br/>
    </body>
    </html>
    复制代码
    复制代码
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
    
    <struts>
        <!-- 开启debug模式,会自动加载配置文件等等,不用每次更改了配置文件就去重新启动下服务器 -->
        <constant name="struts.devMode" value="true" />
        
        <!-- 配置action -->
        <package name="downLoad" extends="struts-default">
            <action name="download1" class="com.fuwh.model.DownloadAction">
                <!-- 
                    inputPath:为action中的inputPath注入值
                    contentType:设置返回的mime类型,默认是text/plain
                    contentLength:返回的流的字节数
                    inputName:chain action中的InputStream的名字,默认是inputStream
                    contentDisposition:下载的文件的名字
                    bufferSize:input 到output的事后的缓存的大小
                    allowCaching:是否允许缓存,默认是true
                    contentCharSet:设置字符编码方式,如果设置一个字符串的话,则会在contentType头文件中
                    添加";charset=value"
                 -->
                <param name="inputPath">/struts.gif</param>
                <result name="success" type="stream">
                    <param name="contentType">image/gif</param>
                    <param name="inputName">inputStream</param>
                    <param name="contentDisposition">filename="struts.gif"</param>
                    <param name="bufferSize">4096</param>
                </result>
            </action>
            <action name="download2" class="com.fuwh.model.DownloadAction">
                <param name="inputPath">a.zip</param>
                <result name="success" type="stream">
                    <param name="contentType">application/zip</param>
                    <param name="inputName">inputStream</param>
                    <param name="contentDisposition">attachment;filename="abcd.zip"</param>
                    <param name="bufferSize">4096</param>
                </result>
            </action>
        </package>
    
    </struts>
    复制代码
    复制代码
    package com.fuwh.model;
    
    import java.io.InputStream;
    
    import org.apache.struts2.ServletActionContext;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class DownloadAction extends ActionSupport{
        
        private static final long serialVersionUID = 1L;
        
        private String inputPath;
        
        
        public String getInputPath() {
            return inputPath;
        }
    
        public void setInputPath(String inputPath) {
            this.inputPath = inputPath;
        }
    
        //必须有这个方法
        public InputStream getInputStream() throws Exception {
            System.out.println("execute getInputStream method");
            System.out.println(inputPath);
            return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
        }
    }
    复制代码

    常用配置

      在struts2里面还提供了一些常用的配置来控制文件的上传。下面三个就是在default.properties中的默认配置

      |-struts.multipart.parser=jakarta

      |-struts.multipart.saveDir=

      |-struts.multipart.maxSize=2097152   //最大上传文件大小(约2M)(是整个请求的大小)

     

    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC 
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 
        "http://struts.apache.org/dtds/struts-2.0.dtd">
    <struts>
        <constant name="struts.multipart.maxSize" value="1000000" />
        ...
    </struts>
    复制代码

      还可以通过配置fileUpload这个拦截器,来控制允许上传的文件类型。

    复制代码
    <action name="doUpload" class="com.example.UploadAction">
        <interceptor-ref name="basicStack"/>
        <interceptor-ref name="fileUpload">
            <param name="allowedTypes">text/plain</param>
        </interceptor-ref> 
        <interceptor-ref name="validation"/>
        <interceptor-ref name="workflow"/>
     
        <result name="success">good_result.jsp</result>
    </action>
    复制代码

      除了使用struts2里面的default.properties还有另外一种配置限制上传文件的大小的方式。

    default.properties的方式主要是出于安全的考虑,防止有人恶意的上传超大文件来占用服务器的空间,这个默认是2M,最大可以设置2G。但是这是整个请求的大小,而不是单个上传的文件的大小,另外一种控制方式,通过拦截器的参数设置,来达到控制单个文件的大小的效果。

    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC 
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 
        "http://struts.apache.org/dtds/struts-2.0.dtd">
    <struts>
        <constant name="struts.multipart.maxSize" value="1000000" />
         
        <action name="doUpload" class="com.example.UploadAction">
            <interceptor-ref name="basicStack"/>
            <interceptor-ref name="fileUpload">
                <param name="maximumSize">500000</param>
            </interceptor-ref> 
            <interceptor-ref name="validation"/>
            <interceptor-ref name="workflow"/>
     
            <result name="success">good_result.jsp</result>
        </action>
    </struts>
    复制代码

      在控制上传文件类型的时候,也是有两种方式的,一种就是前面提到的配置的方式(声明式),另一种就是编程式。

    复制代码
    <action name="doUpload" class="com.example.UploadAction">
        <interceptor-ref name="basicStack"/>
        <interceptor-ref name="fileUpload">
            <param name="allowedTypes">image/jpeg,image/gif</param>
        </interceptor-ref> 
        <interceptor-ref name="validation"/>
        <interceptor-ref name="workflow"/>
     
        <result name="success">good_result.jsp</result>
    </action>
    复制代码

      

  • 相关阅读:
    vue 拖拽移动(类似于iPhone虚拟home )
    鼠标事件-MouseEvent【转】
    JS快速排序 希尔排序 归并排序 选择排序
    JS 继承
    Centos6 iptables 防火墙设置【转】
    centos6 mongodb 安装
    操作系统中涉及的各种调度算法
    循环队列
    队列
    栈(C++)
  • 原文地址:https://www.cnblogs.com/wangsicongde/p/7574264.html
Copyright © 2011-2022 走看看