项目中我们会上传文件直接解析进行数据的传递和存储 一般的文件我们都可以使用读写操作 像excel之类解析也有总结(excel解析http://blog.csdn.net/docuxu/article/details/78326330)下面总结一下上传压缩文件 然后对文件的处理
项目实例以Struts2上传文件解析为例(zip解压缩 里面为excel文件 然后解析) 关于模板生成下载的问题大家可以评论下问
准备除了struts2基础jar包外 还需要 ant-1.7.0.jar 后面上传jar给链接
web.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
上传文件jsp
<%@ page language="java" contentType="text/html; charset=utf8"
pageEncoding="utf8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<title>Insert title here</title>
</head>
<body>
<h1>上传文件</h1>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="some">
<input type="submit" value="提交">
</form>
</body>
</html>
回显文件jsp
<%@ page language="java" contentType="text/html; charset=utf8"
pageEncoding="utf8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<title>Insert title here</title>
</head>
<body>
<h1>上传成功</h1>
</body>
</html>
BaseAction
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;
public class BaseAction implements SessionAware, ServletContextAware,
ServletRequestAware, ServletResponseAware {
protected Map<String,Object> session;
protected HttpServletRequest request;
protected HttpServletResponse response;
protected ServletContext context;
public void setSession(Map<String, Object> arg0) {
// TODO Auto-generated method stub
this.session=arg0;
}
public void setServletContext(ServletContext arg0) {
// TODO Auto-generated method stub
this.context=arg0;
}
public void setServletRequest(HttpServletRequest arg0) {
// TODO Auto-generated method stub
this.request=arg0;
}
public void setServletResponse(HttpServletResponse arg0) {
// TODO Auto-generated method stub
this.response=arg0;
}
public String toRealPath(String path){
return context.getRealPath(path);
}
}
UploadZipAction
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Map.Entry;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class UploadZipAction {
// private File some;//someImage
private String some;
private String someFileName;//**FileName
private String someContentType;//**ContentType
/*
public File getSome() {
return some;
}
public void setSome(File some) {
this.some = some;
}*/
public String getSomeFileName() {
return someFileName;
}
public String getSome() {
return some;
}
public void setSome(String some) {
this.some = some;
}
public void setSomeFileName(String someFileName) {
this.someFileName = someFileName;
}
public String getSomeContentType() {
return someContentType;
}
public void setSomeContentType(String someContentType) {
this.someContentType = someContentType;
}
//拦截器在调用fileUpload在Struts2调用UploadAction的execute方法
//之前进行了拦截 将上传过的文件放入缓存区 然后从缓存区里
//读取文件位置 文件长度 文件名等扥数据 在execute()方法执行之后又进行拦截 将缓存区里的数据清空
public String execute() throws Exception{
System.out.println(some);
System.out.println(someFileName);
File file=new File(some);
Map<String,InputStream> map=ZipUtil.unZipFilesForVuln(file);
System.out.println(map.size());
for(Entry<String, InputStream> entry:map.entrySet()){
if(entry.getKey().contains("/")){
return "success";
}
}
for(Entry<String, InputStream> entry:map.entrySet()){
System.out.println("key:"+entry.getKey()+",value:"+entry.getValue());
VulnFileAn(entry.getValue());
}
return "success";
}
public void VulnFileAn(InputStream is){
String msg = "";
Workbook rwb = null;
try {
rwb=Workbook.getWorkbook(is);
} catch (BiffException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Sheet sheet = rwb.getSheet(0);
int rows = sheet.getRows();// 行数
int columns = sheet.getColumns();// 列数
boolean isModel = false; //! 确认添加标识
//! 校验Excel模板
if (!checkExcel(rwb)) {
//throw new Exception("excel模板不正确");
isModel=true;
System.out.println(isModel);
}else{
if(rows>1){// 文件中的记录大于1
for(int i=1;i<rows;i++){
String id=sheet.getCell(0, i).getContents().trim();
String name = sheet.getCell(1, i).getContents().trim();
String phone = sheet.getCell(2, i).getContents().trim();
String money = sheet.getCell(3, i).getContents().trim();
try {
User user=new User();
user.setId(id);
user.setName(name);
user.setPhone(phone);
user.setMoney(money);
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
if (rwb != null) {
rwb.close();
}
}
private boolean checkExcel(Workbook rwb) {
Sheet sheet = rwb.getSheet(0);
int rows = sheet.getRows();// 行数
int columns = sheet.getColumns();// 列数
String[] heads = new String[] {"用户编号","用户姓名","手机号码","注册资金"};
if (rows > 1 && columns == heads.length) {
for (int i = 0; i < columns; i++) {
String contents = sheet.getCell(i, 0).getContents();
if (contents == null || !contents.equals(heads[i])) {
return false;
}
}
return true;
} else {
return false;
}
}
}
注意:因为用于测试解析效果所以很多异常没有处理 还有文件进入时可以根据后缀进行相应的处理
ps 把excel文件放到一个文件夹中压缩 和直接多选添加到压缩文件文件路径不一致 工具类中我写的方法是多文件添加的路径 你们也可以自己写
ZipUtil工具类
public static Map<String,InputStream> unZipFilesForVuln(File zipfile) {
Map<String,InputStream> map=new HashMap<String,InputStream>();
try {
// Open the ZIP file
ZipFile zf = new ZipFile(zipfile);
for (Enumeration entries = zf.getEntries(); entries.hasMoreElements();) {
// Get the entry name
ZipEntry entry = ((ZipEntry) entries.nextElement());
String zipEntryName = entry.getName();
System.out.println(zipEntryName);
InputStream in = zf.getInputStream(entry);
//list.add(in);
map.put(zipEntryName, in);
// in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
注意:需要用到第三方jar
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<package name="upload" namespace="/" extends="struts-default">
<!-- 返回上传界面 -->
<action name="uploadform">
<interceptor-ref name="basicStack"></interceptor-ref>
<result name="success">/WEB-INF/uploadform.jsp</result>
</action>
<!-- 发送上传请求 -->
<action name="upload" class="com.xms.action.UploadZipAction">
<interceptor-ref name="fileUpload"></interceptor-ref>
<interceptor-ref name="basicStack"></interceptor-ref>
<result name="success">/WEB-INF/uploadImage.jsp</result>
</action>
</package>
</struts>
User类
import java.io.Serializable;
public class User implements Serializable{
private String id;
private String name;
private String phone;
private String money;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
@Override
public String toString() {
return "User [id=" + id + ", money=" + money + ", name=" + name
+ ", phone=" + phone + "]";
}
}
excel内容
将1.xls 2.xls打包压缩到33.zip 上传33.zip
console 打印效果
33.zip
2.xls
1.xls
2
key:2.xls,value:java.util.zip.InflaterInputStream@2d9351c6
User [id=1002, money=50000000, name=wanwan, phone=12345678902]
key:1.xls,value:java.util.zip.InflaterInputStream@2a8d025e
User [id=1001, money=50000000, name=docuxu, phone=12345678901]