您的位置:首页 > 编程语言 > Java开发

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

2016-12-08 18:02 501 查看
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视图对应的错误页面。

 

<!--配置错误视图-->
<result name="input">/cx/error.jsp</result>


通过文件后缀名

<!--限制运行上传文件的类型-->
<interceptor-ref name="defaultStack">
<param name="fileUpload.allowedExtensions">txt,jpg</param>
</interceptor-ref>


通过文件类型
<!--限制运行的类型-->
<param name="fileUpload.allowedTypes">text/plain</param>


两个同时写,就取交集

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: