因为今天写项目的时候用到了,struts2去实现文件上传的功能,感觉相对与以前用servlet实现上传简单了不少,于是,今天就来总结以下struts2的文件上传功能的实现。
三要素
一,表单的提交方式必须是post方法。
- get方式不能,是因为get方式有上传有大小的限制。
二,在form表单上一定要设置enctype=“multipart/form-data”,不然无法上传成功。
三,一定要有< input type=“file” name=“upload” >
- 在struts2中上传一定要给上传文件的那个input,上添加上name属性,因为struts2上传文件需要用到name里面的这个值。
比如(最简单的一个上传文件的form):
<form action="uploadAction_upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="upload"/></br>
<input type="submit" value="提交"/>
</form>
action
上传文件时候我们需要创建一个action,但是我们在这个action里面需要添加如下东西。
一定要给他们添加上set方法,不然不会成功。
private String uploadFileName; //上传文件的名称
private String uploadContentType;//上传文件的类型
private File upload;//文件
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public void setUpload(File upload) {
this.upload = upload;
}
注意:在这里这个三个变量的命名是有规范的,满足如下规则,
< input type=“file” name=“你自己的命名”/>,那么这三个变量的命名就是:
上传文件的名称
name的值 + FileName
上传文件的类型
name的值 + ContentType
文件
name的值
相关举例如下
① < input type=“file” name=“xxx”/>,那么三个变量的命名就是:
private String xxxFileName; //上传文件的名称
private String xxxContentType;//上传文件的类型
private File xxx;//文件
② < input type=“file” name=“ooo”/>,那么三个变量的命名就是:
private String oooFileName; //上传文件的名称
private String oooContentType;//上传文件的类型
private File ooo;//文件
以上便是最简单的struts2的文件上传。
完整案例说明
附带struts2相关变量的配置。
1,web.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Summary_1</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 配置struts的核心过滤器 -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2,创建action
package com.items.test.web.action;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private String uploadFileName; // 上传文件的名称
private String uploadContentType;// 上传文件的类型
private File upload;// 文件
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String upload() throws IOException {
String dstPath = "D://" + uploadFileName;
System.out.println(dstPath);
if(upload != null) {
File dstFile = new File(dstPath);
FileUtils.copyFile(upload, dstFile);
}
return NONE;
}
}
3,创建一个index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:fielderror></s:fielderror>
<form action="uploadAction_upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="upload"/></br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
4,struts.xml的配置
<?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>
<!--配置struts的常量-->
<constant name="struts.action.extension" value="action"/>
<!-- 配置Struts2中所上传的文件的总大小 -->
<constant name="struts.multipart.maxSize" value="5242880"/>
<package name="one" extends="struts-default" namespace="/">
<action name="uploadAction_*" class="com.items.test.web.action.UploadAction" method="{1}">
<result name="input">/index.jsp</result>
<interceptor-ref name="defaultStack">
<!-- 上传文件时的限制条件,只允许,上传后缀名时 txt jpg -->
<param name="fileUpload.allowedExtensions">.txt,.jpg</param>
<!-- 上传一个文件的大小 -->
<param name="fileUpload.maximumSize">5105120</param>
</interceptor-ref>
</action>
</package>
</struts>
下面详细说明一下:
①在UploadAction中的upload()方法中我们会使用到 FileUtils.copyFile();
注意:FileUtils的全路径的是 org.apache.commons.io.FileUtils 不要把包导错了。
②struts.xml中的配置信息:
-
< param name=“fileUpload.allowedExtensions”> </ param >
作用是:用于限制文件上传的后缀名。
eg:
1,只能上传后缀为jpg格式的文件
< param name=“fileUpload.allowedExtensions”>.jpg</ param >
2,如果我们想要限制多个后缀名的化,中间我们用逗号隔开
< param name=“fileUpload.allowedExtensions”>.jpg, .txt, .png</ param > -
< param name=“fileUpload.maximumSize”></ param >
作用是:设置上传文件的大小。
1,如果我们想要设置不要超过5M的文件大小
< param name=“fileUpload.maximumSize”>5242880</ param > -
< constant name=“struts.multipart.maxSize” value=""/>
作用是:设置上传文件总的大小。
注意:这个设置与< param name=“fileUpload.maximumSize”></ param >有所不同,这里是总的大小。
eg:比如我们想要上传多个文件(将action中设置的三个变量变成数组就可以了,其他的不变)
假设我们的form变成了如下样式:这个时候便是多文件上传。
< constant name=“struts.multipart.maxSize” value=""/> 表示的是这次文件上传总共文件大小不要超过多少。
< param name=“fileUpload.maximumSize”></ param >表示的是一个文件的大小不要超过多少。
<form action="uploadAction_upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="upload"/></br>
<input type="file" name="upload"/></br>
<input type="file" name="upload"/></br>
<input type="submit" value="提交"/>
</form>
最后我们需要注意一个东西,比如说,我们在本地上传时,从 此电脑的 c://a.txt 上传到此电脑的 c://a.txt注意这个时候上传会报错!!!!!!
上传文件过多或者重复上传
重复上传:我们可以用随机命名来解决。
上传文件过多:比如说我们上传文件时,到同一个文件,里面文件数目过多,那么我们在以后查找的时候速度可能会下降,所以我们需要使用多级目录。
下面是相关工具类
package com.items.crm.utils;
import java.util.UUID;
public class UploadUtils {
/**
* 获取随机名称
* @param realName 真实名称
* @return uuid
*/
public static String getUUIDName(String realName){
//realname 可能是 1.jpg 也可能是 1
//获取后缀名
int index = realName.lastIndexOf(".");
if(index==-1){
return UUID.randomUUID().toString().replace("-", "").toUpperCase();
}else{
return UUID.randomUUID().toString().replace("-", "").toUpperCase()+realName.substring(index);
}
}
/**
* 获取文件真实名称
* @param name
* @return
*/
public static String getRealName(String name){
// c:/upload/1.jpg 1.jpg
//获取最后一个"/"
int index = name.lastIndexOf("\\");
return name.substring(index+1);
}
/**
* 获取文件目录:根据文件名称获取8级目录
* @param name 文件名称
* @return 目录
*/
public static String getDir(String name){
int i = name.hashCode();
String hex = Integer.toHexString(i);
int j=hex.length();
for(int k=0;k<8-j;k++){
hex="0"+hex;
}
String dir = "";
for(i=0;i<8;i++) {
dir += "/"+hex.charAt(i);
}
return dir;
}
@SuppressWarnings("unused")
public static void main(String[] args) {
//String s="G:\\day17-基础加强\\resource\\1.jpg";
String s="1.jgp";
String realName = getRealName(s);
//System.out.println(realName);
String uuidName = getUUIDName(realName);
System.out.println(uuidName);
String dir = getDir(uuidName);
System.out.println(dir);
/**
*
/4/a/d/f/e/d/2/4
295CEE7309684A13A2A789505A004EC7.jgp
*
*/
}
}