struts-基础内容-7-文件上传

Struts的文件上传

文件上传拦截器作用,默认就执行

源码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.apache.struts2.interceptor;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.LocaleProvider;
import com.opensymphony.xwork2.TextProvider;
import com.opensymphony.xwork2.TextProviderFactory;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.util.PatternMatcher;
import com.opensymphony.xwork2.util.TextParseUtil;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;

public class FileUploadInterceptor extends AbstractInterceptor {
    private static final long serialVersionUID = -4764627478894962478L;
    protected static final Logger LOG = LoggerFactory.getLogger(FileUploadInterceptor.class);
    protected Long maximumSize;
    protected Set<String> allowedTypesSet = Collections.emptySet();
    protected Set<String> allowedExtensionsSet = Collections.emptySet();
    private PatternMatcher matcher;
    private Container container;

    public FileUploadInterceptor() {
    }

    @Inject
    public void setMatcher(PatternMatcher matcher) {
        this.matcher = matcher;
    }

    @Inject
    public void setContainer(Container container) {
        this.container = container;
    }

    public void setAllowedExtensions(String allowedExtensions) {
        this.allowedExtensionsSet = TextParseUtil.commaDelimitedStringToSet(allowedExtensions);
    }

    public void setAllowedTypes(String allowedTypes) {
        this.allowedTypesSet = TextParseUtil.commaDelimitedStringToSet(allowedTypes);
    }

    public void setMaximumSize(Long maximumSize) {
        this.maximumSize = maximumSize;
    }

    public String intercept(ActionInvocation invocation) throws Exception {
        ActionContext ac = invocation.getInvocationContext();
        HttpServletRequest request = (HttpServletRequest)ac.get("com.opensymphony.xwork2.dispatcher.HttpServletRequest");
        if(!(request instanceof MultiPartRequestWrapper)) {
            if(LOG.isDebugEnabled()) {
                ActionProxy var18 = invocation.getProxy();
                LOG.debug(this.getTextMessage("struts.messages.bypass.request", new String[]{var18.getNamespace(), var18.getActionName()}), new String[0]);
            }

            return invocation.invoke();
        } else {
            ValidationAware validation = null;
            Object action = invocation.getAction();
            if(action instanceof ValidationAware) {
                validation = (ValidationAware)action;
            }

            MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper)request;
            String inputName;
            if(multiWrapper.hasErrors()) {
                Iterator fileParameterNames = multiWrapper.getErrors().iterator();

                while(fileParameterNames.hasNext()) {
                    inputName = (String)fileParameterNames.next();
                    if(validation != null) {
                        validation.addActionError(inputName);
                    }
                }
            }

            Enumeration var19 = multiWrapper.getFileParameterNames();

            while(var19 != null && var19.hasMoreElements()) {
                inputName = (String)var19.nextElement();
                String[] contentType = multiWrapper.getContentTypes(inputName);
                if(!this.isNonEmpty(contentType)) {
                    if(LOG.isWarnEnabled()) {
                        LOG.warn(this.getTextMessage(action, "struts.messages.invalid.content.type", new String[]{inputName}), new String[0]);
                    }
                } else {
                    String[] fileName = multiWrapper.getFileNames(inputName);
                    if(!this.isNonEmpty(fileName)) {
                        if(LOG.isWarnEnabled()) {
                            LOG.warn(this.getTextMessage(action, "struts.messages.invalid.file", new String[]{inputName}), new String[0]);
                        }
                    } else {
                        File[] files = multiWrapper.getFiles(inputName);
                        if(files != null && files.length > 0) {
                            ArrayList acceptedFiles = new ArrayList(files.length);
                            ArrayList acceptedContentTypes = new ArrayList(files.length);
                            ArrayList acceptedFileNames = new ArrayList(files.length);
                            String contentTypeName = inputName + "ContentType";
                            String fileNameName = inputName + "FileName";

                            for(int params = 0; params < files.length; ++params) {
                                if(this.acceptFile(action, files[params], fileName[params], contentType[params], inputName, validation)) {
                                    acceptedFiles.add(files[params]);
                                    acceptedContentTypes.add(contentType[params]);
                                    acceptedFileNames.add(fileName[params]);
                                }
                            }

                            if(!acceptedFiles.isEmpty()) {
                                Map var20 = ac.getParameters();
                                var20.put(inputName, acceptedFiles.toArray(new File[acceptedFiles.size()]));
                                var20.put(contentTypeName, acceptedContentTypes.toArray(new String[acceptedContentTypes.size()]));
                                var20.put(fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()]));
                            }
                        }
                    }
                }
            }

            return invocation.invoke();
        }
    }

    protected boolean acceptFile(Object action, File file, String filename, String contentType, String inputName, ValidationAware validation) {
        boolean fileIsAcceptable = false;
        String errMsg;
        if(file == null) {
            errMsg = this.getTextMessage(action, "struts.messages.error.uploading", new String[]{inputName});
            if(validation != null) {
                validation.addFieldError(inputName, errMsg);
            }

            if(LOG.isWarnEnabled()) {
                LOG.warn(errMsg, new String[0]);
            }
        } else if(this.maximumSize != null && this.maximumSize.longValue() < file.length()) {
            errMsg = this.getTextMessage(action, "struts.messages.error.file.too.large", new String[]{inputName, filename, file.getName(), "" + file.length(), this.getMaximumSizeStr(action)});
            if(validation != null) {
                validation.addFieldError(inputName, errMsg);
            }

            if(LOG.isWarnEnabled()) {
                LOG.warn(errMsg, new String[0]);
            }
        } else if(!this.allowedTypesSet.isEmpty() && !this.containsItem(this.allowedTypesSet, contentType)) {
            errMsg = this.getTextMessage(action, "struts.messages.error.content.type.not.allowed", new String[]{inputName, filename, file.getName(), contentType});
            if(validation != null) {
                validation.addFieldError(inputName, errMsg);
            }

            if(LOG.isWarnEnabled()) {
                LOG.warn(errMsg, new String[0]);
            }
        } else if(!this.allowedExtensionsSet.isEmpty() && !this.hasAllowedExtension(this.allowedExtensionsSet, filename)) {
            errMsg = this.getTextMessage(action, "struts.messages.error.file.extension.not.allowed", new String[]{inputName, filename, file.getName(), contentType});
            if(validation != null) {
                validation.addFieldError(inputName, errMsg);
            }

            if(LOG.isWarnEnabled()) {
                LOG.warn(errMsg, new String[0]);
            }
        } else {
            fileIsAcceptable = true;
        }

        return fileIsAcceptable;
    }

    private String getMaximumSizeStr(Object action) {
        return NumberFormat.getNumberInstance(this.getLocaleProvider(action).getLocale()).format(this.maximumSize);
    }

    private boolean hasAllowedExtension(Collection<String> extensionCollection, String filename) {
        if(filename == null) {
            return false;
        } else {
            String lowercaseFilename = filename.toLowerCase();
            Iterator i$ = extensionCollection.iterator();

            String extension;
            do {
                if(!i$.hasNext()) {
                    return false;
                }

                extension = (String)i$.next();
            } while(!lowercaseFilename.endsWith(extension));

            return true;
        }
    }

    private boolean containsItem(Collection<String> itemCollection, String item) {
        Iterator i$ = itemCollection.iterator();

        String pattern;
        do {
            if(!i$.hasNext()) {
                return false;
            }

            pattern = (String)i$.next();
        } while(!this.matchesWildcard(pattern, item));

        return true;
    }

    private boolean matchesWildcard(String pattern, String text) {
        Object o = this.matcher.compilePattern(pattern);
        return this.matcher.match(new HashMap(), text, o);
    }

    private boolean isNonEmpty(Object[] objArray) {
        boolean result = false;

        for(int index = 0; index < objArray.length && !result; ++index) {
            if(objArray[index] != null) {
                result = true;
            }
        }

        return result;
    }

    protected String getTextMessage(String messageKey, String[] args) {
        return this.getTextMessage(this, messageKey, args);
    }

    protected String getTextMessage(Object action, String messageKey, String[] args) {
        return action instanceof TextProvider?((TextProvider)action).getText(messageKey, args):this.getTextProvider(action).getText(messageKey, args);
    }

    private TextProvider getTextProvider(Object action) {
        TextProviderFactory tpf = new TextProviderFactory();
        if(this.container != null) {
            this.container.inject(tpf);
        }

        LocaleProvider localeProvider = this.getLocaleProvider(action);
        return tpf.createInstance(action.getClass(), localeProvider);
    }

    private LocaleProvider getLocaleProvider(Object action) {
        LocaleProvider localeProvider;
        if(action instanceof LocaleProvider) {
            localeProvider = (LocaleProvider)action;
        } else {
            localeProvider = (LocaleProvider)this.container.getInstance(LocaleProvider.class);
        }

        return localeProvider;
    }
}

文件上传步骤

写upload.jsp

<%--
  Created by IntelliJ IDEA.
  User: cxspace
  Date: 16-7-9
  Time: 下午11:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
   <form action="${pageContext.request.contextPath}/fileUploadAction" method="post" enctype="multipart/form-data">
          用户名:<input type="text" name="userName"> <br>
          文件:<input type="file" name="file1"><br>
         <input type="submit" value="上传">
     </form>
</body>
</html>

配置action

<?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>
    <package name="upload_" extends="struts-default">

        <!--action名称不能用fileUpload-->
        <action name="fileUploadAction" class="com.cx.fileupload.FileUpload">
          <result name="success">/cx/success.jsp</result>
        </action>

    </package>
</struts>

action类

package com.cx.fileupload;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import java.io.File;

/**
 * Created by cxspace on 16-7-10.
 */
public class FileUpload extends ActionSupport{
    //对应表单
    private File file1;

    //文件名
    private String file1FileName;  // 必须加FileName后缀

    //文件类型
    private String file1ContentType;  //必须加ContentType后缀

    public void setFile1(File file1) {
        this.file1 = file1;
    }

    public void setFile1FileName(String file1FileName) {
        this.file1FileName = file1FileName;
    }

    public void setFile1ContentType(String file1ContentType) {
        this.file1ContentType = file1ContentType;
    }

    @Override
    public String execute() throws Exception {

        System.out.println("上传ok");
        //获取上传的路径
        String path = ServletActionContext.getServletContext().getRealPath("/upload");
        File deskfile = new File(path,file1FileName);
        //把文件上传到upload目录
        FileUtils.copyFile(file1,deskfile);
        return SUCCESS;
    }

}

文件上传处理细节

文件大小限制

默认大小的限制2M

  <!--修改上传文件的最大大小限制,增大为30m,在struts.xml中配置常量-->
    <constant name="struts.multipart.maxSize" value="31457280"></constant>

限制文件后缀

通过拦截器注入参数,从而限制文件上传类型

错误提示

当文件上传出现错误的时候,struts内部会返回input视图(错误视图)。所以需要在struts.xml中配置input视图对应的错误页面。

时间: 2024-10-16 11:18:48

struts-基础内容-7-文件上传的相关文章

转:在Struts 2中实现文件上传

前一阵子有些朋友在电子邮件中问关于Struts 2实现文件上传的问题, 所以今天我们就来讨论一下这个问题. 实现原理 Struts 2是通过Commons FileUpload文件上传.Commons FileUpload通过将HTTP的数据保存到临时文件夹,然后Struts使用fileUpload拦截器将文件绑定到Action的实例中.从而我们就能够以本地文件方式的操作浏览器上传的文件. 具体实现 前段时间Apache发布了Struts 2.0.6 GA,所以本文的实现是以该版本的Struts

struts(八)文件上传

文件上传简述 struts2的文件上传没有使用Servlet 3.0 API,所以struts2的文件上传还需要依赖于Common-FileUpload.COS等文件上传组件. 为了能上传文件,必须将表单的method设置为POST,将enctype设置为multipart/form-data,需添加 < input type="file"> 字段.这样,浏览器才会把用户选择文件的二进制数据发送给服务器. 设置了enctype为multipart/form-data,浏览器

利用Struts拦截器完成文件上传功能

Struts2的图片上传以及页面展示图片 在上次的CRUD基础上加上图片上传功能 (https://www.cnblogs.com/liuwenwu9527/p/11108611.html) 文件上传:三种上传方案1.上传到tomcat服务器2.上传到指定文件目录,添加服务器与真实目录的映射关系,从而解耦上传文件与tomcat的关系文件服务器3.在数据库表中建立二进制字段,将图片存储到数据库(现在基本不用了) 我们使用第二种方法实现图片上传 实现效果如下: 首先是展示页面 clzList.jsp

SpringMVC基础(二)_文件上传、异常处理、拦截器

实现文件上传 实现文件上传,需要借助以下两个第三方 jar 包对上传的二进制文件进行解析: commons-fileupload commons-io form表单的 enctype 取值必须为:multipart/form-data(默认为:application/x-www-form-urlencoded):enctype为表单请求正文的类型:method 属性必须取值为 post 方式:提供一个文件选择域: <input type="file"/> : <for

Struts学习之 实现文件上传、下载操作

一.Struts-cofig.xml流程图 二.register.jsp页面文件 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1

python——基础篇-简易文件上传

post_server import socket import os sk=socket.socket() address=('127.0.0.1',8000) sk.bind(address) sk.listen(3) print('waiting...') BASE_DIR=os.path.dirname(os.path.abspath(__file__)) while 1: conn,addr=sk.accept() while 1: data=conn.recv(1024) cmd,f

php基础练习--多文件上传

<html> <head> <meta charset="utf-8"> <title>index_uploads</title> </head> <body> <form action="uploads.php" method="post" enctype="multipart/form-data"> <input type

Struts2单文件上传原理及示例

一.文件上传的原理 表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值: 1.application/x-www-form-urlencoded:这是默认编码方式,它只处理表单域里的value属性值,采用这种编码方式的表单会将表单域的值处理成URL编码方式. 2.multipart/form-data:这种编码方式的表单会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数里. 3.text/plain:这种方式主要适用于直接通过表单发送邮件的

5文件上传与下载

java领域有两个常用的文件上传项目:Common-FileUpload和COS.struts2则在原来的文件上传的项目基础上,进行进一步的封装,从而进一步地简化了文件上传.除此之外,struts2对文件下载支持stream的结果类型,通过借助于struts2提供的文件下载支持,应用可以实现非西欧字符文件名的文件下载,并可以在文件下载前检查用户的权限,从而通过授权控制来控制文件的下载. 文件上传原理 表单元素的enctype属性 大部分时候,无需设置表单元素的enctype属性,我们只设置表单的

文件上传到tomcat服务器 commons-fileupload的详细介绍与使用

三个类:DiskFileUpload.FileItem和FileUploadException.这三个类全部位于org.apache.commons.fileupload包中. 首先需要说明一下form表格的enctpye的属性: 表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码.默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传:只有使用了multipart/form-data,