1、前端jsp页面代码,前端没有文件格式的验证:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath(); //获取当前项目名称
//request.getScheme():协议名称
//request.getServerName():服务器地址
//request.getServerPort():端口号
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
</head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="<%=basePath%>file/fileUpload.do" enctype="multipart/form-data">
<table align="center">
<tr>
<td>压缩文件:</td>
<td><input type="file" name="compressedFile" value="请选择要上传的文件..."></td>
</tr>
<tr>
<td></td>
<td><input type="submit" align="middle" value="提交"></td>
</tr>
</table>
</form>
<form method="post" action="<%=basePath%>file/parseExcel.do" enctype="multipart/form-data">
<table align="center">
<tr>
<td>Excel文件:</td>
<td><input type="file" name="xlsFile" value="请选择要上传的文件..."></td>
</tr>
<tr><br/></tr>
<tr>
<td></td>
<td><input type="submit" align="middle" value="提交"></td>
</tr>
</table>
</form>
</body>
</html>
2、Controller层:
package com.wolfhome.fileupload.controller;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.wolfhome.fileupload.service.FileUploadService;
import com.wolfhome.fileupload.utils.DeleteFilesRecursionUtil;
/**
* <p>ClassName:FileUplodeController</p>
* @功能描述 文件上传
* <p>Company:wolfhome</p>
* @author Hrzhi
* @date 2017年11月27日 下午6:15:41
*/
@Controller
@RequestMapping("/file")
public class FileUploadController {
private static Logger logger = Logger.getLogger(FileUploadController.class);
@Autowired
private FileUploadService service;
@RequestMapping("/fileUpload.do")
public String fileUpload(@RequestParam(value = "compressedFile") MultipartFile file, HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>();// 用于保存响应信息
logger.info(file.getSize());
// 如果上传问价为null或者上传文件大小为0,则直接响应错误信息
if (file == null || file.getSize() == 0) {
map.put("success", "fail");
map.put("msg", "压缩文件为空,请检查文件内容!");
} else {
// 获取文件的名字
String fileName = file.getOriginalFilename();
logger.debug("originalFileName:" + file.getOriginalFilename());
// 获取文件名的后缀格式
String suffixFileName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
logger.info(suffixFileName);
// 如果不是zip格式的文件或者未上传文件,则返回错误页面
if (StringUtils.isBlank(fileName) || (!".zip".equals(suffixFileName) && !".rar".equals(suffixFileName))) {
// 返回提示信息
map.put("success", "fail");
map.put("msg", "没有要上传的文件或上传文件格式不正确,请检查文件!");
} else {
// 获取指定文件夹的目录
String filePath = request.getSession().getServletContext().getRealPath("/upload");
// 根据文件路径个文件名称创建File对象
File tempFile = new File(filePath, fileName);
// 如果文件夹不存在,则创建文件夹
if (!tempFile.exists()) {
// newFile.delete();
// 如果文件夹不存在,则创建文件夹
tempFile.mkdirs();
}
try {
// 上传文件到目标路径下
file.transferTo(tempFile);
// 调用Service层的方法处理压缩包
map = service.fileHaddle(tempFile, request);
if (map.get("msg") != null || "".equals(map.get("msg"))) {
map.put("success", "fail");
//解析异常,则删除所有文件
DeleteFilesRecursionUtil.deleteFileRecursion(tempFile.getParentFile());
}else {
map.put("success", "success");
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//删除压缩文件
tempFile.delete();
}
}
}
return (String) map.get("success");
}
}
3、Service层逻辑处理
package com.wolfhome.fileupload.service.impl;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.wolfhome.fileupload.domain.User;
import com.wolfhome.fileupload.service.FileUploadService;
import com.wolfhome.fileupload.utils.UncompressionUtlis;
/**
* <p>ClassName:FileUploadService</p>
* @功能描述 文件上传逻辑处理接口实现类
* <p>Company:wolfhome</p>
* @author Hrzhi
* @date 2017年11月28日 上午10:15:47
*/
@Service
public class FileUploadServiceImpl implements FileUploadService {
private Logger logger = Logger.getLogger(FileUploadServiceImpl.class);
/**
* 文件处理方法
*
* @param file
* @param request
* @return
*/
@Override
public Map<String, Object> fileHaddle(File file, HttpServletRequest request) {
List<File> fileList = null;// fileList中存放压缩包内解压出来的文件列表
Map<String, Object> map = new HashMap<>();// map里面存放返回信息
List<User> datalist = null;// 存放excel里面解析出来的对象
List<File> attachmentList = new ArrayList<>();// 存放附件
String msg = null;
logger.info("目标文件的绝对路径是:" + file.getAbsolutePath());
String fileName = file.getName();
//如果是.zip格式的压缩文件,则调用UncompressionUtlis.unZipFile方法
if (".zip".equals(fileName.substring(fileName.lastIndexOf(".")).toLowerCase())) {
fileList = UncompressionUtlis.unZipFile(file.getAbsolutePath(), file.getParent());
//如果是.rar格式的压缩文件,则调用UncompressionUtlis.unRarFile方法
} else if (".rar".equals(fileName.substring(fileName.lastIndexOf(".")).toLowerCase())) {
fileList = UncompressionUtlis.unRarFile(file.getAbsolutePath(), file.getParent());
} else {
// 暂不处理
}
// return "success";
map.put("msg", msg);
return map;
}
}
4、重点:文件解压工具类:
package com.wolfhome.fileupload.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.log4j.Logger;
import de.innosystec.unrar.Archive;
import de.innosystec.unrar.rarfile.FileHeader;
/**
* <p>ClassName:UnZipFilesUtil</p>
* @功能描述 压缩包解压工具类
* <p>@Company:wolfhome</p>
* @author Hrzhi
* @date 2017年11月28日 上午11:27:54
*/
public class UncompressionUtlis {
private static Logger logger = Logger.getLogger(UncompressionUtlis.class);
/**
* zip文件解压
*
* @param file
* 要解压的文件
* @param targetPath
* 解压后的地址
* @throws IOException
*/
public static List<File> unZipFile(String filePath, String targetPath) {
return unZipFile(new File(filePath), targetPath);
}
/**
* zip解压文件
*
* @param file
* 要解压的文件
* @param targetPath
* 解压后的地址
*/
public static List<File> unZipFile(File file, String targetPath) {
List<File> fileList = new LinkedList<>();// 用于保存解压后的文件
InputStream ins = null;
FileOutputStream fout = null;
ZipFile zipFile = null;
// 解压文件
try {
zipFile = new ZipFile(file, Charset.forName("GBK"));
// 根据targetPath创建文件夹
File newFile = new File(targetPath, file.getName().substring(0, file.getName().lastIndexOf(".")));
if (newFile.exists()) {
newFile.delete();
}
newFile.mkdirs();
// 遍历获取每一个文件
for (@SuppressWarnings("rawtypes")
Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
logger.info("zipEntryName:" + zipEntryName);
File entryFile = new File(newFile, zipEntryName);
if (entry.isDirectory()) {
entryFile.mkdirs();
} else {
// 获取该文件的输入流
ins = zipFile.getInputStream(entry);
fout = new FileOutputStream(entryFile);
int length = 0;
byte[] b = new byte[1024];
// 将实体写到文件中去
while ((length = ins.read(b, 0, 1024)) != -1) {
fout.write(b, 0, length);
}
// 将文件保存到list集合中
fileList.add(entryFile);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 解压完成后删除压缩包
file.delete();
try {
if (zipFile != null) {
zipFile.close();
}
} catch (IOException e) {
e.printStackTrace();
}
// 关闭输入流
try {
ins.close();
} catch (IOException e) {
e.printStackTrace();
}
// 关闭输出流
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return fileList;
}
/**
* rar格式的压缩文件解压缩
*
* @param file
* 要解压缩的文件
* @param targetPath
* 解压后文件的保存路径
* @return list
*/
public static List<File> unRarFile(String filePath, String targetPath) {
return unRarFile(new File(filePath), targetPath);
}
// 方法重载
/**
* rar格式的压缩文件解压缩
*
* @param file
* 要解压缩的文件
* @param targetPath
* 解压后文件的保存路径
* @return list
*/
public static List<File> unRarFile(File file, String targetPath) {
List<File> fileList = new LinkedList<>();
Archive archive = null;
FileOutputStream fos = null;
try {
// 根据targetPath创建文件夹
File newFile = new File(targetPath, file.getName().substring(0, file.getName().lastIndexOf(".")));
/*if (!newFile.exists()) {
newFile.mkdirs();
}*/
archive = new Archive(file.getAbsoluteFile());
FileHeader fh = archive.nextFileHeader();
while (fh != null) {
if (!fh.isDirectory()) {
// 1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
String compressFileName = fh.getFileNameW().trim();
String destFileName = "";
String destDirName = "";
// 非windows系统
if (File.separator.equals("/")) {
destFileName = newFile + compressFileName.replaceAll("\\\\", "/");
destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
} else {
// windows系统
destFileName = newFile + "\\" + compressFileName.replaceAll("/", "\\\\");
destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
}
fileList.add(new File(destFileName));
// 2创建文件夹
File dir = new File(destDirName);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
// 3解压缩文件
fos = new FileOutputStream(new File(destFileName));
archive.extractFile(fh, fos);
fos.close();
fos = null;
}
fh = archive.nextFileHeader();
}
archive.close();
archive = null;
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
logger.info(fileList.toString());
return fileList;
}
}
5、文件及文件夹递归删除:
package com.wolfhome.fileupload.utils;
import java.io.File;
/**
* <p>@ClassName:DeleteFilesRecursionUtil</p>
* @功能描述 递归删除文件及文件夹
* <p>@Company:wolfhome</p>
* @author Hrzhi
* @date 2017年12月12日 下午8:39:54
*/
public class DeleteFilesRecursionUtil {
public static void deleteFileRecursion(File parentFile) {
//获取目录下的所有文件包括文件夹组成的list集合
File[] listFiles = parentFile.listFiles();
//遍历文件集合,删除文件
for (File file : listFiles) {
if (file.isDirectory()) {
//递归调用
deleteFileRecursion(file);
}
file.delete();
}
parentFile.delete();
}
}