zoukankan      html  css  js  c++  java
  • Struts2(十五)实现文件上传

    一、导入包

    • 需要将commons-fileupload和commons-io包和struts包一起导入

    实现步骤:

    1. 在Jsp页面实现客户端选择上传文件
    2. 配置Struts.xml,拦截器会自动接收上传的文件
    3. 在Action中实现代码上传文件存入服务器中
    4. 跳转至新页面展示上传的文件

    二、单个文件上传

    上传页面

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>单个文件上传</title>
    </head>
    <body>
    <form action="doUpload.action" method="post" enctype="multipart/form-data">
    <input type="file" name="upload"/>
    <input type="submit" value="上传">
    </form>
    </body>
    </html>

    上传成功页面

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        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>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>文件上传成功</title>
    </head>
    <body>
    <h1>上传的文件</h1>
    <img alt="图片" src="<s:property value='savePath'/>" />
    
    </body>
    </html>

    UploadAction

    package com.pb.web.action;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import org.apache.commons.io.IOUtils;
    import org.apache.struts2.ServletActionContext;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class UploadAction extends ActionSupport {
    
        //上传文件全路径、类型、文件名
        private File upload;
        private String uploadContentType;
        private String uploadFileName;
        //新文件保存路径和名称
        private String savePah;
    
        public String doUpload() throws IOException{
            System.out.println(upload);
            System.out.println(uploadContentType);
            System.out.println(uploadFileName);
            String newFileName=System.currentTimeMillis()+uploadFileName.substring(uploadFileName.lastIndexOf("."));
            System.out.println("新的文件名:"+newFileName);
            //获取上传路径
            savePah=ServletActionContext.getServletContext().getRealPath("/upload/"+newFileName);
            System.out.println("上传保存的路径和名称:"+savePah);
            //使用文件输入、输出流写入文件
            FileInputStream fis=new FileInputStream(upload);
            FileOutputStream fos=new FileOutputStream(savePah);
            //设置缓冲区大小
            /*byte[] bytes=new byte[1024];
            //读取文件
            int length=fis.read(bytes);
            while(length>0){
                //写入文件
                fos.write(bytes);
                length=fis.read(bytes);
            }*/
            //复制文件
            IOUtils.copy(fis, fos);
            fos.flush();
            fos.close();
            fis.close();
            
            return SUCCESS;
        }
    
    
        public File getUpload() {
            return upload;
        }
    
    
        public void setUpload(File upload) {
            this.upload = upload;
        }
    
    
        public String getUploadContentType() {
            return uploadContentType;
        }
    
    
        public void setUploadContentType(String uploadContentType) {
            this.uploadContentType = uploadContentType;
        }
    
    
        public String getUploadFileName() {
            return uploadFileName;
        }
    
    
        public void setUploadFileName(String uploadFileName) {
            this.uploadFileName = uploadFileName;
        }
    
    
        public String getSavePah() {
            return savePah;
        }
    
    
        public void setSavePah(String savePah) {
            this.savePah = savePah;
        }
        
        
        
    }

    struts.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
    
    <struts>
    
        <constant name="struts.enable.DynamicMethodInvocation" value="false" />
        <constant name="struts.devMode" value="true" />
       <package name="default" namespace="/" extends="struts-default">
        <action name="doUpload" class="com.pb.web.action.UploadAction" method="doUpload">
        <result name="success">
        /singleUploadSuccess.jsp
        </result>
        <result name="error">
        /error.jsp
        </result>
        <result name="input">
        /singleUpload.jsp
        </result>
        </action>
        </package>
    </struts>

    三、限制文件大小

    • 在struts.xml中配置常量
    <constant name="struts.multipart.maxSize" value="5000000"/>
    5M大小

    在action下配置拦截器

    <interceptor-ref name="fileUpload">
        <param name="maximumSize">5000000</param>    
        </interceptor-ref>
        <interceptor-ref name="defaultStack"></interceptor-ref>

    五、限制文件类型

    <interceptor-ref name="fileUpload">
        <param name="allowedTypes">image/pjpeg,image/jpeg,image/gif,image/png</param>
        <param name="maximumSize">5000000</param>    
        </interceptor-ref>
        <interceptor-ref name="defaultStack"></interceptor-ref>

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
    
    <struts>
    
        <constant name="struts.enable.DynamicMethodInvocation" value="false" />
        <constant name="struts.devMode" value="true" />
        <constant name="struts.multipart.maxSize" value="1000000" />
        <constant name="struts.multipart.saveDir" value="/tmp"/>
        <package name="default" namespace="/" extends="struts-default">
        <action name="doupload" class="com.pb.web.action.UploadAction" method="upload">
        <interceptor-ref name="fileUpload">
                <param name="maximumSize">40000</param>
                 <param name="allowedTypes">image/jpeg,image/pjpeg,image/gif,image/png</param>
            </interceptor-ref> 
            <interceptor-ref name="defaultStack"></interceptor-ref>
        <result name="success">
        /oneUploadSuccess.jsp
        </result>
        <result name="input">
        /error.jsp
        </result>
        </action>
        </package>
    </struts>

    六、多个文件上传

    和单个文件上传一个只是接收参数变为数组

    mulUpload.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>多个 文件上传</title>
    <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
    <script type="text/javascript">
    function addFile(){
        /*  获取父元素*/
        var parent=$("#add").parent();
        /*创建新的节点  */
        var file=$("<input type='file' name='upload' /><br/>");
        /* 添中节点 */
        parent.append(file);
        
    }
    </script>
    </head>
    <body>
    <form action="doupload.action" method="post" enctype="multipart/form-data">
    <input type="file" name="upload" />
    <input type="button" value="继续添加"  onclick="addFile();" id="add"/>
    <input type="submit" value="上传" /><br/>
    </form>
    </body>
    </html>

    error.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        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>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>上传失败</title>
    </head>
    <body>
    上传失败<a href="mulUpload.jsp">返回</a>
    <s:debug/>
    </body>
    </html>

    mulUploadSuccess.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        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>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>上传成功</title>
    </head>
    <body>
    <!--显示上传的图片  -->
    <s:iterator value="savePath" var="i">
    <img alt="图片" src="<s:property value='#i'/>">
    </s:iterator>
    <s:debug/>
    </body>
    </html>

    UploadAction.java

    package com.pb.web.action;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.commons.io.IOUtils;
    import org.apache.struts2.ServletActionContext;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class UploadAction extends ActionSupport {
        // 文件上传路径、类型、名称
        private List<File> upload;
        private List<String> uploadFileName;
        private List<String> uploadContentType;
        // 新的文件名称
        private List<String> savePath=new ArrayList<String>();
    
        public String upload() throws IOException {
            for (int i = 0; i < upload.size(); i++) {
                //重命名 用长时间+原来的文件名
                String newFileName = System.currentTimeMillis()+""+uploadFileName.get(i);
                System.out.println("新的文件名:"+newFileName);
            //获取上传路径
                //将新的路径和名称添加入集合
                savePath.add(ServletActionContext.getServletContext().getRealPath("/upload/"+newFileName));
                System.out.println(savePath.get(i));
                //读取文件
                FileInputStream fis=new FileInputStream(upload.get(i));
                //写入文件
                FileOutputStream fos=new FileOutputStream(savePath.get(i));
                //将文件从输入流,复制到输出流中
                IOUtils.copy(fis, fos);
                //强制刷新输出流,清空缓冲区
                fos.flush();
                fos.close();
                fis.close();
            }
    
            return SUCCESS;
        }
    
        public List<File> getUpload() {
            return upload;
        }
    
        public void setUpload(List<File> upload) {
            this.upload = upload;
        }
    
        public List<String> getUploadFileName() {
            return uploadFileName;
        }
    
        public void setUploadFileName(List<String> uploadFileName) {
            this.uploadFileName = uploadFileName;
        }
    
        public List<String> getUploadContentType() {
            return uploadContentType;
        }
    
        public void setUploadContentType(List<String> uploadContentType) {
            this.uploadContentType = uploadContentType;
        }
    
        public List<String> getSavePath() {
            return savePath;
        }
    
        public void setSavePath(List<String> savePath) {
            this.savePath = savePath;
        }
    
    
    }

    struts.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
    
    <struts>
    
        <constant name="struts.enable.DynamicMethodInvocation" value="false" />
        <constant name="struts.devMode" value="true" />
        <!--设置文件大小拦截器  -->
        <constant name="struts.multipart.maxSize" value="10000000"></constant>
        
        <constant name="struts.multipart.saveDir" value="/tmp"/>
        <package name="default" namespace="/" extends="struts-default">
        <action name="doupload" class="com.pb.web.action.UploadAction" method="upload">
        
        <interceptor-ref name="fileUpload">
        <!--设置文件类型拦截器  -->
        <param name="allowedTypes">image/jpeg,image/pjpeg,image/png</param>
        <!--设置文件大小拦截器  -->
        <param name="maximumSize">5000000</param>
        </interceptor-ref>
        <!-- struts默认的拦截器 -->
        <interceptor-ref name="defaultStack" />
        
        <result name="success">
        /mulUploadSuccess.jsp
        </result>
        <result name="input">
        /error.jsp
        </result>
        </action>
        </package>
    </struts>

    更详细的请参考:struts下载包中的帮助文档:

    file://stuts2/struts2-2.3.4.1-all/struts-2.3.4.1/docs/WW/file-upload.html

  • 相关阅读:
    cxf简单实例
    生成素描图片
    Robotlegs2 学习笔记 -- SwiftSuspenders 2.x (2)
    Robotlegs2 学习笔记 -- SwiftSuspenders 2.x (1)
    Spring boot的put请求 (如何实现RestFul Api风格)
    net start npf启用失败
    vue项目中:‘vue-cli-service' 不是内部或外部命令,也不是可运行的程序或批处理文件的报错
    SpringBoot + Mybatis 打印sql语句修改配置文件的方式
    vue-cli最新脚手架的安装
    SpringBoot项目中设置日期返回的格式
  • 原文地址:https://www.cnblogs.com/liunanjava/p/4389661.html
Copyright © 2011-2022 走看看